【问题标题】:How to test an async method in Windows Phone如何在 Windows Phone 中测试异步方法
【发布时间】:2013-03-07 01:48:24
【问题描述】:

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

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

我收到一条错误消息,提示“pots”不可等待。 Pots 是一个列表,它应该接受来自对我的 web 服务进行异步调用的 potholes 函数的结果。

这是使用 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

【问题讨论】:

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


    【解决方案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();
            });
    }
    

    【讨论】:

      【解决方案2】:

      正如 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();
          }
      }
      

      【讨论】:

        【解决方案3】:

        您以错误的方式使用 async .. await

        试试这个

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-31
          • 2016-01-11
          相关资源
          最近更新 更多