问题描述
我有一个看起来像这样的方法:
I have a method that looks like this:
private async void DoStuff(long idToLookUp)
{
IOrder order = await orderService.LookUpIdAsync(idToLookUp);
// Close the search
IsSearchShowing = false;
}
//Other stuff in case you want to see it
public DelegateCommand<long> DoLookupCommand{ get; set; }
ViewModel()
{
DoLookupCommand= new DelegateCommand<long>(DoStuff);
}
我想进行单元测试这样的:
I am trying to unit test it like this:
[TestMethod]
public void TestDoStuff()
{
//+ Arrange
myViewModel.IsSearchShowing = true;
// container is my Unity container and it setup in the init method.
container.Resolve<IOrderService>().Returns(orderService);
orderService = Substitute.For<IOrderService>();
orderService.LookUpIdAsync(Arg.Any<long>())
.Returns(new Task<IOrder>(() => null));
//+ Act
myViewModel.DoLookupCommand.Execute(0);
//+ Assert
myViewModel.IsSearchShowing.Should().BeFalse();
}
,不然我和嘲笑了LookUpIdAsync做我的断言被调用。在我的正常code,这就是我想要的。但是,对于我的单元测试,我不希望出现这种情况。
My assert is called before I get done with the mocked up LookUpIdAsync. In my normal code, that is just what I want. But for my Unit test I don't want that.
我使用的BackgroundWorker转换为异步/等待。随着后台工作,这是正常工作,因为我可以等待BackgroundWorker的完成。
I am converting to Async/Await from using BackgroundWorker. With background worker this was functioning correctly because I could wait for the BackgroundWorker to finish.
但似乎没有成为一个方式来等待一个异步方法无效...
But there does not seem to be a way to wait for a async void method...
如何单元测试这种方法?
推荐答案
我想出了一个办法做到这一点的单元测试:
I figured out a way to do it for unit testing:
[TestMethod]
public void TestDoStuff()
{
//+ Arrange
myViewModel.IsSearchShowing = true;
// container is my Unity container and it setup in the init method.
container.Resolve<IOrderService>().Returns(orderService);
orderService = Substitute.For<IOrderService>();
var lookupTask = Task<IOrder>.Factory.StartNew(() =>
{
return new Order();
});
orderService.LookUpIdAsync(Arg.Any<long>()).Returns(lookupTask);
//+ Act
myViewModel.DoLookupCommand.Execute(0);
lookupTask.Wait();
//+ Assert
myViewModel.IsSearchShowing.Should().BeFalse();
}
这里的关键是,因为我的单元测试,我可以在我想有我的异步调用(我的异步空内)返回任务替代。然后,我只是确保之前,我继续前进的任务已经完成了。
The key here is that because I am unit testing I can substitute in the task I want to have my async call (inside my async void) to return. I then just make sure the task has completed before I move on.
这篇关于等待一个异步虚空方法调用的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!