I have created a sample WPF MVVM project which I now want to Unit test. The viewmodels load the data asynchronously in the constructor:
public class CustomerOverviewViewModel
{
public CustomerOverviewViewModel()
{
var t = LoadFullCustomerListAsync();
}
public async Task LoadFullCustomerListAsync()
{
List<BL_acc> customers = await Task.Run(() => // Query from db);
}
}
In WPF, this works like a charm. When I want to create a unit test for this viewmodel, I create the object by calling its default constructor:
[TestMethod]
public void Test()
{
customerOverviewViewModel = new CustomerOverviewViewModel();
// Do the test
}
However, the unit test has no way of knowing when the async method is finished. Can this be fixed using constructor initialization or should I use a different pattern?
Edit
The unit tests don't need the async loaded information, they just need an instance of the class to test the methods. It just seems like a lot of extra work to use another initialization method just for my unit tests.
All the unit tests succeed but they sometimes throw an error that multiple threads try to access the same context (which disappears when the data is not loaded async):
The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.