【问题标题】:Writing Unit tests for Continuation tasks in .Net在 .Net 中为继续任务编写单元测试
【发布时间】:2013-02-08 02:16:46
【问题描述】:

我是单元测试的新手,我正在尝试为使用任务的 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。

【问题讨论】:

  • 您真正想要测试的内容。通过查看代码,我看不到您尝试进行单元测试的任何重要行为。

标签: .net unit-testing c#-4.0 task


【解决方案1】:

您可以添加一个同步原语来等待。如果您不希望在生产构建中出现这种情况,您可以使用 #if _DEBUG#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");
        }

    }
}

【讨论】:

  • 谢谢,我当然可以使用这种技术,但只是想在使用此方法之前检查是否有更优雅的方法,或者我的设计是否有问题。使用基于事件的异步模式不是更好地编写可以更好地进行单元测试的代码而不是 TPL 异步吗?
猜你喜欢
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
相关资源
最近更新 更多