检测财产异步方法设置 [英] Testing property set by async method
问题描述
我尝试测试与NUnit的一类,它包含异步方法。我不知道该怎么做以正确的方式。
I try to test a class with NUnit that contains async methods. I don't know how to do it in a correct way.
我有一个类是这样的:
public class EditorViewModel:INotifyPropertyChanged
{
public void SetIdentifier(string identifier)
{
CalcContentAsync();
}
private async void CalcContentAsync()
{
await SetContentAsync();
DoSomething();
}
private async Task SetContentAsync()
{
Content = await Task.Run<object>(() => CalculateContent());
RaisePropertyChanged("Content");
}
public object Content { get; private set; }
...
}
我怎么能写NUnit的测试,即检查,该内容属性设置为正确的价值?我想要做这样的事情:
How can I write a Test in NUnit, that checks, that the Content-Property is set to the right value? I want to do something like that:
[Test]
public void Content_WhenModifierIsXXX_ReturnsSomeViewModel()
{
var viewModel = new EditorViewModel();
viewModel.SetIdentifier("XXX");
Assert.That(viewModel.Content, Is.InstanceOf<ISomeContentViewModel>());
}
但是,这并不工作。由于异步code尚未断言之前执行。
But that doesn't work. Because the asynchronous code has not been executed before the assertion.
推荐答案
您 SetIdentifier
方法异步
太(或者你需要使它异步
,因为你等着里面的操作然后,你的方法可以看起来像下一个:
Your SetIdentifier
method is async
too (or you need to make it async
because you wait operation inside it. Then your method can looks like next one:
public async Task SetIdentifier(string identifier)
{
await SetContentAsync();
DoSomething();
}
而现在你可以等待它在你的单元测试:
And now you can just await it in your unit test:
[Test]
public async Task Content_WhenModifierIsXXX_ReturnsSomeViewModel()
{
var viewModel = new EditorViewModel();
await viewModel.SetIdentifier("XXX");
Assert.That(viewModel.Content, Is.InstanceOf<ISomeContentViewModel>());
}
您也可以使用变通方法来调用您的测试在同步方式:
You can also use workaround to call your test in a sync manner:
[Test]
public async Task Content_WhenModifierIsXXX_ReturnsSomeViewModel()
{
Task.Run(async () =>
{
var viewModel = new EditorViewModel();
await viewModel.SetIdentifier("XXX");
Assert.That(viewModel.Content, Is.InstanceOf<ISomeContentViewModel>());
}).GetAwaiter().GetResult();
}
这篇关于检测财产异步方法设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!