Moq Async callback error with multiple parameters

I am trying to train if this is what I am doing wrong, or its problem is moq or NUnit. I call the endpoint of the soap, and my service link generates both synchronous and asynchronous methods. The call I make looks something like this:

public async Task DoThisAsync(idnameobject myobj, int id) { await ws.DoSomethingAsync(myobj, id); } 

I am setting my moq to return a callback, so I can associate the parameters with which I called the web service. My test looks something like this:

 var callback = new idnameobject(); wsMock .SetUp(w => w.DoSomethingAsync(It.IsAny<idnameobject>(), It.IsAny<int>()) .Callback<idnameobject, int>((obj, id) => callback = obj); await myservice.DoThisAsync(myobj, id); Assert.That(callback.Id, Is.EqualTo(myobj.Id)); 

At this point, I get a null reference exception when calling my method, which does not contain any information in the stack trace. All I have is an Exception thrown: 'System.AggregateException' in mscorlib.dll in the output.

The bit, which is strange, is that it will not work if I configure the callback from the synchronous method and change my method to call it.

It also doesn't crash if I call the async method, which has only one parameter.

If anyone has any ideas, let me know because I don’t want to change my method because of our tests, but ideally I want my test to provide the correct access to the web service.

+8
c # asynchronous tdd nunit moq
source share
1 answer

You are mocking ws.DoSomethingAsync() , but do not set it to return. The DoThisAsync() method will fail because it will try to wait for a null value. You can fix this by changing the setup code to

 wsMock.SetUp(w => w.DoSomethingAsync(It.IsAny<idnameobject>(), It.IsAny<int>()) .Callback<idnameobject, int>((obj, id) => callback = obj) .Returns(Task.FromResult(0)); 

If you are using .NET 4.6 or higher, you can replace Task.FromResult(0) with Task.CompletedTask .

+20
source share

All Articles