【发布时间】:2019-06-03 10:30:16
【问题描述】:
我正在尝试对命令进行单元测试,但由于它是异步命令,因此测试方法会在命令完成之前进入断言。我已经查找了这个问题的解决方案,他们都在谈论创建一个我不想做的 AsyncCommand 接口等,因为我只需要等待用于单元测试目的的命令。那么是否有另一种更简单且不需要创建另一个接口等的解决方案?
这是我的命令类:
public class Command : ICommand
{
public void Execute(object parameter)
{
//exeute...
}
//other stuff....
}
那是被测试的类:
pubic class MyClass
{
private Command commandForTest;
public Command CommandForTest
{
get
{
if (commandForTest == null)
{
commandForTest = new Command(async (o) =>
{
if(someCondition)
await SomeMethod();
else
await AnotheMrthod();
});
}
return commandForTest;
}
}
}
这是测试方法:
[TestMethod]
public async Task Test()
{
MyClass myclass = new MyClass();
await Task.Run( () => myclass.CommandForTest.Execute());
//Assert....
}
【问题讨论】:
-
我没有使用太多命令,但你可以试试这个页面:johnthiriet.com/mvvm-going-async-with-async-command/#
-
不要测试命令,这是 UI 的东西。而是创建一个该命令调用的公共可测试方法。
-
您不能等待从未明确表示已完成的事情。这正是
Task存在的原因,以及异步的void方法无法有效测试的原因。无法编写测试并不是测试失败,而是代码失败。
标签: c# multithreading unit-testing async-await icommand