如何在Windows Phone中测试异步方法

时间:2013-03-07 01:48:25

标签: unit-testing windows-phone-7 asynchronous restsharp

我需要在Windows Phone中编写一个单元测试来测试我的数据是否被反序列化为正确的类型。这是我到目前为止所做的。

[TestMethod]
    [Asynchronous]
    public void SimpleTest()
    {
        await pots = help.potholes();

我收到一个错误,说“盆”不是等待的。 Pots是一个列表,它应该接受来自potholes函数的结果,该函数正在对我的web服务进行异步调用。

这是使用Restsharp进行调用的方法。

public void GetAllPotholes(Action<IRestResponse<List<Pothole>>> callback)
    {

        var request = new RestRequest(Configuration.GET_POTHOLE_ALL,Method.GET);
        request.AddHeader("Accept", "application/json");
        _client.ExecuteAsync(request, callback);

    }

我怎样才能制作罐子?什么是在Windows Phone中测试休息服务的正确方法?

我正在使用Windows Phone Toolkit测试框架

这是我正在关注的教程。 Asynchronous tests

3 个答案:

答案 0 :(得分:1)

术语“异步”现在在.net中重载。

您引用的文章是指awaitable方法,而不是通过回调异步的方法。

以下是对如何测试这一点的粗略概念。

[TestMethod]        
[Asynchronous]
public void SimpleTest()
{
    // set up your system under test as appropriate - this is just a guess
    var help = new HelpObject();

    help.GetAllPotholes(
        response =>
        {
            // Do your asserts here. e.g.
            Assert.IsTrue(response.Count == 1);

            // Finally call this to tell the test framework that the test is now complete
            EnqueueTestComplete();
        });
}

答案 1 :(得分:1)

as matt表示术语异步现在正在多个上下文中使用,对于Windows Phone上的测试方法,正如您在代码中看到的那样,不是关键字,而是一个目标是释放工作线程允许其他进程运行,并且您的测试方法可以等待UI或服务请求中可能发生的任何更改。

你可以做这样的事情让你的考试等待。

[TestClass]
public class ModuleTests : WorkItemTest
{
    [TestMethod, Asynchronous]
    public void SimpleTest()
    {
        var pots;
        EnqueueDelay(TimeSpan.FromSeconds(.2)); // To pause the test execution for a moment.
        EnqueueCallback(() => pots = help.potholes());
        // Enqueue other functionality and your Assert logic
        EnqueueTestComplete();
    }
}

答案 2 :(得分:0)

你正在使用async .. await以错误的方式

试试这个

public async void SimpleTest()
{
    pots = await help.potholes();
    ....
}