c# - xUnit and Moq do not support async - await keywords -
i trying discover how apply async , await keywords xunit tests. using xunit 1.9 , async ctp 1.3. here test case
i have interface specifies 1 asynchronous method call
public interface idostuffasync { task anasyncmethod(string value); } i have class consumes interface , calls async method
public class useanasyncthing { private readonly idostuffasync _dostuffasync; public useanasyncthing(idostuffasync dostuffasync) { _dostuffasync = dostuffasync; } public async task dothatasyncoperation(string thevalue) { await _dostuffasync.anasyncmethod(thevalue); } } in tests wish check method dothatasyncoperation calling method correct value mock interface , use moq verify call
[fact] public async void the_test_will_pass_even_though_it_should_fail() { var mock = new mock<idostuffasync>(); var sut = new useanasyncthing(mock.object); mock.setup(x => x.anasyncmethod(it.isany<string>())); await sut.dothatasyncoperation("test"); // won't throw moq.mockexcpetion test appears pass // not run mock.verify(x => x.anasyncmethod("fail")); } this test using async , await keywords. when runs erroneously passes moq should assert verify fails. code after call sut.dothatasyncoperation("test"); not run
[fact] public void this_will_work_and_assert_the_reslt() { var mock = new mock<idostuffasync>(); var sut = new useanasyncthing(mock.object); mock.setup(x => x.anasyncmethod(it.isany<string>())); sut.dothatasyncoperation("test").continuewith(y => { }); // won't throw moq.mockexcpetion test appears pass // not run mock.verify(x => x.anasyncmethod("fail")); } this test setup without await , async keywords , passes fine.
is expected behavior xunit , moq?
update
thanks stephen's comment managed fix first test making 2 changes. test returns task instead of void , mock returns task.
[fact] public async task the_test_will_pass_even_though_it_should_fail() { var mock = new mock<idostuffasync>(); var sut = new useanasyncthing(mock.object); mock.setup(x => x.anasyncmethod(it.isany<string>())).returnasync(true); await sut.dothatasyncoperation("test"); // fails should mock.verify(x => x.anasyncmethod("fail")); }
change unit test method return task instead of void, , should work. support async void unit tests is being considered future release.
i describe in detail why async unit tests don't work default on blog. (my blog examples use mstest, same problems existed in every other test runner, including xunit pre-1.9).
Comments
Post a Comment