gpt4 book ai didi

c# - 异步 CTP,单元测试 ViewModel 的异步方法

转载 作者:行者123 更新时间:2023-11-30 13:12:22 24 4
gpt4 key购买 nike

我有一个像这样的单元测试(使用 MSTest):

[TestMethod]
public void MyTest()
{
var viewModel = new MyViewModel();
viewModel.Run();
//Assert something here
}

Run 是一个返回 void 的异步方法。

假设Run是这样实现的:

public async void Run()
{
//Show a busy indicator here

try
{
var result = await myAsyncModelClass.LongRunningOperation();

//Use the results here
}
finally
{
//Hide the busy indicator here
}
}

myAsyncModelClass.LongRunningOperation() , 本身就是一个返回一些 Task<T> 的异步方法其中 T 是我的 ViewModel 感兴趣的结果。

我的问题是,我的测试正在运行 Run异步方法,因此我的断言在 Run 之前被调用方法完成。奇怪的是,当我放置断点时,b/c 永远不会到达 finally block ,因为断言失败了。我怎样才能保留 Run方法同步就可以单元测试了吗?

我有一个 myAsyncModelClass.LongRunningOperation() 的单元测试也,但我只是调用Task<T>.Wait()因为它返回一个任务。这使得它在单元测试时同步。

另外,我想提一下,Run()由 ICommand 神奇地由 MVVM 框架调用。 void可能需要也可能不需要返回类型,我将不得不尝试一下。

最佳答案

异步方法需要一个上下文来“返回”。由于 MSTests 在线程池上运行,默认情况下异步方法也会在线程池线程上继续(并且不会阻止 MSTest 方法)。

(C# Testing) Unit Testing 示例(在您的 Async CTP 安装目录中)下,有一个名为 GeneralThreadAffineContext 的类型,可以这样使用:

[TestMethod]
public void MyTest()
{
MyViewModel viewModel = null;
GeneralThreadAffineContext.Run(() =>
{
viewModel = new MyViewModel();
viewModel.Run();
});
//Assert something here
}

还有特定的 WPF 和 WinForms 上下文,但是线程仿射上下文应该适用于一般的 ViewModel(不显式使用 Dispatcher)。

2012-02-05 更新:如果您可以更改 ViewModel 方法以返回 Task,那么您还有另一个选择:新的 AsyncUnitTests library .安装该 NuGet 包,将 TestClass 更改为 AsyncTestClass,您的异步单元测试可以编写得更自然:

[TestMethod]
public async void MyTest()
{
MyViewModel viewModel = new MyViewModel();
await viewModel.Run();
//Assert something here
}

2012-09-04 更新:Visual Studio 2012 包含async 单元测试,因此您不再需要AsyncUnitTests 库:

[TestMethod]
public async Task MyTest()
{
MyViewModel viewModel = new MyViewModel();
await viewModel.Run();
//Assert something here
}

关于c# - 异步 CTP,单元测试 ViewModel 的异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7260715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com