These are my business engine's methods. Upload is calling internally async method UploadAsync()
public void Upload(Stream data) { //Some logic //Call private async method UploadAsync(data); } private async void UploadAsync(Object data) { await Task.Run(() => { using (var factory = new DataRepositoryFactoryObject<IAllCommandRepository>(DataRepositoryFactory)) { factory.Repository.UploadData(data); } } ); } This is unit test case for Upload() method
[TestMethod, TestCategory("Unit")] public void Upload_ValidData_Success() { //other logic to setup mock repository //call public method which calls async method engine.Upload(data); _mockAllCommandRepository.Verify(x => x.Upload(It.Is<Object>(t => t != null)), Times.Once); } This test case is getting failed occasioally at verify method with following exception:
016-10-06T19:25:20.4982657Z ##[error]Expected invocation on the mock once, but was 0 times: x => x.Upload(It.Is<Object>(t => t != null)), Times.Once); As per my analysis verify method gets called before calling async method. This can be reason of failure of this test case. How can I verify that a method was called on a mock when the method itself is called in a delegate passed to Task.Run? By time mock.Verify is called the Task still hasn't executed. Could anyone please provide some solution so that this test case will pass each and every time
Uploadasync Task?async voidmethod. Don't useasync void, especially in this case. It's meant only for event handlers or similar functions. This isn't the case here. There are even warnings by Resharper and Roslyn about incorrect usage ofasync voidUploadAsync, eg checking whether the upload completed, or if the server returns a 500 error.async void, and even how to write a Unit Test against it: haacked.com/archive/2014/11/11/async-void-methods