影响单元测试的构造函数中的异步方法
Async method within constructor affecting unit tests
进行单元测试,测试仅在 Jobs.Count > 0
时才允许导航。
GetJobsAsync()
在构造期间调用,如果不为空则清除作业列表(每次调用时获取新列表)。在我手动添加新作业作为单元测试通过的条件后,作业列表似乎被清除了。我如何获得正确的时间,以便在 运行 测试期间不清除作业列表?
在MyClass构造函数中:
this.GetJobsAsync();
GetJobsAsync:
private async void GetJobsAsync()
{
var jobs = await this.dataService.GetJobs();
if (jobs != null)
{
this.Jobs.Clear();
foreach (var job in jobs)
{
this.Jobs.Add(new JobViewModel(job));
}
}
// have the select job command rerun its condition
this.SelectJobCommand.RaiseCanExecuteChanged();
}
单元测试(必须至少有一个job用于导航,jobs添加后清空):
var vm = new MyClass();
vm.Jobs.Add(new JobVM(new JobModel()));
vm.SelectJobCommand.Execute(null);
Assert.AreEqual(
NavigationKeys.WizardJob,
this.navigationService.CurrentPageKey);
It appears that the Jobs list is cleared after I manually add a new job as a condition for the unit test to pass.
很明显,您了解自己存在竞争条件。您无法在 async void
上等待,并且您在构造函数中。
How do I get this timing correct so that the Jobs list isn't cleared during the running of the test?
两件事。首先,将 GetJobAsync
更改为 async Task
而不是 async void
。然后,使用异步初始化模式:
public class MyClass
{
public Task InitializeAsync()
{
return GetJobsAsync();
}
}
并且在你的单元测试中:
public async Task TestNavigationAsync()
{
var vm = new MyClass();
await vm.InitializeAsync();
vm.Jobs.Add(new JobVM(new JobModel()));
vm.SelectJobCommand.Execute(null);
Assert.AreEqual(NavigationKeys.WizardJob,
navigationService.CurrentPageKey);
}
这样可以保证执行顺序
进行单元测试,测试仅在 Jobs.Count > 0
时才允许导航。
GetJobsAsync()
在构造期间调用,如果不为空则清除作业列表(每次调用时获取新列表)。在我手动添加新作业作为单元测试通过的条件后,作业列表似乎被清除了。我如何获得正确的时间,以便在 运行 测试期间不清除作业列表?
在MyClass构造函数中:
this.GetJobsAsync();
GetJobsAsync:
private async void GetJobsAsync()
{
var jobs = await this.dataService.GetJobs();
if (jobs != null)
{
this.Jobs.Clear();
foreach (var job in jobs)
{
this.Jobs.Add(new JobViewModel(job));
}
}
// have the select job command rerun its condition
this.SelectJobCommand.RaiseCanExecuteChanged();
}
单元测试(必须至少有一个job用于导航,jobs添加后清空):
var vm = new MyClass();
vm.Jobs.Add(new JobVM(new JobModel()));
vm.SelectJobCommand.Execute(null);
Assert.AreEqual(
NavigationKeys.WizardJob,
this.navigationService.CurrentPageKey);
It appears that the Jobs list is cleared after I manually add a new job as a condition for the unit test to pass.
很明显,您了解自己存在竞争条件。您无法在 async void
上等待,并且您在构造函数中。
How do I get this timing correct so that the Jobs list isn't cleared during the running of the test?
两件事。首先,将 GetJobAsync
更改为 async Task
而不是 async void
。然后,使用异步初始化模式:
public class MyClass
{
public Task InitializeAsync()
{
return GetJobsAsync();
}
}
并且在你的单元测试中:
public async Task TestNavigationAsync()
{
var vm = new MyClass();
await vm.InitializeAsync();
vm.Jobs.Add(new JobVM(new JobModel()));
vm.SelectJobCommand.Execute(null);
Assert.AreEqual(NavigationKeys.WizardJob,
navigationService.CurrentPageKey);
}
这样可以保证执行顺序