基本上,我有一个调用事件处理程序的方法。事件处理程序调用异步方法,我需要知道该方法的结果(true 或 false)。由于事件处理程序只能返回 void,因此我创建了自己的EventArgssuccess 属性,如果运行正常,我会在该方法中将其设置为 true。
public virtual async Task<bool> TrySomething()
{
var args = new MyEventArgs();
SomeEvent?.Invoke(this, args);
return args.Success;
}
Run Code Online (Sandbox Code Playgroud)
SomeEvent连接到SomeEventHandler
private async void SomeEventHandler(object sender, MyEventArgs e)
{
e.Success = await AnAsyncMethod();
}
private asyc Task<bool> AnAsyncMethod()
{
//...
}
Run Code Online (Sandbox Code Playgroud)
我感到困惑的是,是否有任何保证该方法TrySomething将等待SomeEvent完成所以Success已经设置,然后返回它?如果没有,我怎样才能确保它能做到呢?
我正在尝试对命令进行单元测试,但是因为它是一个异步命令,所以在命令完成之前,测试方法会进入断言。我已经查找了这个问题的解决方案,他们都在谈论创建一个 AsyncCommand 接口等,我不想这样做,因为我只需要等待用于单元测试目的的命令。那么是否有另一种更简单的解决方案,不需要创建另一个界面等?
这是我的命令类:
public class Command : ICommand
{
public void Execute(object parameter)
{
//exeute...
}
//other stuff....
}
Run Code Online (Sandbox Code Playgroud)
那是测试类:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是测试方法:
[TestMethod]
public async Task Test()
{
MyClass myclass = new MyClass();
await Task.Run( () => myclass.CommandForTest.Execute());
//Assert....
}
Run Code Online (Sandbox Code Playgroud)