c# - How to Unit test ViewModel with async initialization in WPF -
i have created sample wpf mvvm project want unit test. viewmodels load data asynchronously in constructor:
public class customeroverviewviewmodel { public customeroverviewviewmodel() { var t = loadfullcustomerlistasync(); } public async task loadfullcustomerlistasync() { list<bl_acc> customers = await task.run(() => // query db); } } in wpf, works charm. when want create unit test viewmodel, create object calling default constructor:
[testmethod] public void test() { customeroverviewviewmodel = new customeroverviewviewmodel(); // test } however, unit test has no way of knowing when async method finished. can fixed using constructor initialization or should use different pattern?
edit
the unit tests don't need async loaded information, need instance of class test methods. seems lot of work use initialization method unit tests.
all unit tests succeed throw error multiple threads try access same context (which disappears when data not loaded async):
the context cannot used while model being created. exception may thrown if context used inside onmodelcreating method or if same context instance accessed multiple threads concurrently. note instance members of dbcontext , related classes not guaranteed thread safe.
in wpf, works charm.
sort of. written, "initialization" task ignored. so, there's no error handling, , there's no indication ui initialization in progress or completed (i.e., there's no way know when show spinner).
in other words, surfacing information (state as as resulting data) useful more unit test code. have straightforward data-bindable task wrapper wrote while ago in situations this.
there isn't alternative way detect completion of asynchronous methods if return task; you'd have expose task somehow. think best way of exposing type wrote, ui can make use of well.
Comments
Post a Comment