Adr*_*ien 4 c# unit-testing task-parallel-library
我有一个图形方法CancelChanges()使用和ViewModel调用.我想测试这个方法,但我们内部有一个Task.我们使用Task来不冻结UI.我的测试方法需要等待此任务的结果来检查结果.
代码是:
public override void CancelChanges()
{
Task.Run(
async () =>
{
this.SelectedWorkflow = null;
AsyncResult<IncidentTypeModel> asyncResult = await this.Dataprovider.GetIncidentTypeByIdAsync(this.Incident.Id);
Utils.GetDispatcher().Invoke(
() =>
{
if (asyncResult.IsError)
{
WorkflowMessageBox.ShowException(
MessageHelper.ManageException(asyncResult.Exception));
}
else
{
this.Incident = asyncResult.Result;
this.Refreshdesigner();
this.HaveChanges = false;
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
而我的测试方法:
/// <summary>
/// A test for CancelChanges
/// </summary>
[TestMethod]
[TestCategory("ConfigTool")]
public void CancelChangesTest()
{
string storexaml = this._target.Incident.WorkflowXamlString;
this._target.Incident.WorkflowXamlString = "dsdfsdgfdsgdfgfd";
this._target.CancelChanges();
Assert.IsTrue(storexaml == this._target.Incident.WorkflowXamlString);
Assert.IsFalse(this._target.HaveChanges);
}
Run Code Online (Sandbox Code Playgroud)
我们如何让我的测试等待任务的结果?
谢谢.
使CancelChanges方法返回a Task,然后等待或在测试方法中设置延续.有些人喜欢这样
public override Task CancelChanges()
{
return Task.Factory.StartNew(() =>
{
// Do stuff...
});
}
Run Code Online (Sandbox Code Playgroud)
注意从变化Task.Run到Task.Factory.StartNew.在这种情况下,这是启动任务的更好方法.然后在测试方法中
[TestMethod]
[TestCategory("ConfigTool")]
public void CancelChangesTest()
{
string storexaml = this._target.Incident.WorkflowXamlString;
this._target.Incident.WorkflowXamlString = "dsdfsdgfdsgdfgfd";
this._target.CancelChanges().ContinueWith(ant =>
{
Assert.IsTrue(storexaml == this._target.Incident.WorkflowXamlString);
Assert.IsFalse(this._target.HaveChanges);
});
}
Run Code Online (Sandbox Code Playgroud)
您还可以将测试方法标记为async并await在测试方法中使用以执行相同的操作.
我希望这有帮助.