2

我是单元测试的新手,并尝试为使用任务的 WPF ViewModel 编写单元测试。我在 VM 中有一个方法连接到 WPF 中的按钮。下面的代码总结了我正在尝试做的事情。类 MainPageViewModel { 私有 IService 服务_;

    public void StartTask()
    {
        var task = service_.StartServiceAsync();
        task.ContinueWith(AfterService);
    }

    private void AfterService(Task<IResult> result)
    {
        //update UI with result
    }
}

class TestClass
{
    [TestMethod]
    public Test_StartTask()
    {
        MainPageViewModel vm = new MainPageViewModel();
        vm.StartTask();
        //need to check if UI is updated but since the AfterService is called on a different thread the assert fails

    }
}

在我的测试方法中,我无法在 StartTask() 调用后编写 Assert,请帮助我了解如何处理此类情况?TIA。

4

1 回答 1

0

您可以添加一个同步原语来等待。如果您不希望在生产构建中出现这种情况,您可以使用#if _DEBUGor来保护它#if UNIT_TEST(其中UNIT_TEST为特定于测试的构建配置定义)。

class MainPageViewModel
{
    private IService service_;
    public AutoResetEvent UpdateEvent = new AutoResetEvent(false);

    public void StartTask()
    {
        var task = service_.StartServiceAsync();
        task.ContinueWith(AfterService);
    }

    private void AfterService(Task<IResult> result)
    {
        //update UI with result
        UpdateEvent.Set();
    }
}

class TestClass
{
    [TestMethod]
    public Test_StartTask()
    {
        MainPageViewModel vm = new MainPageViewModel();
        vm.StartTask();
        if( vm.UpdateEvent.WaitOne(5000) ) {
           // check GUI state
        } else {
           throw new Exception("task didn't complete");
        }

    }
}
于 2013-02-08T02:57:15.697 回答