Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq Async Callback Fails with multiple parameters

I'm trying to workout if it is something I am doing wrong, or its an issue in moq or NUnit. I am calling a soap endpoint and my service reference is generating both sync and async methods. The call I am making, looks something like:

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

I am setting up my moq to return the callback, so I can interegate the parameters I have called the web service with. My test looks something like:

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 doesn't contain any information in the stack trace. All I have is Exception thrown: 'System.AggregateException' in mscorlib.dll in the output.

The bit that is strange, is that it does not fail if I setup the callback from the synchronous method and change my method to call that.

It also does not fail if I call an async method that only has one parameter.

If anyone has any ideas, please let me know as I don't want to change my method because of our tests, but ideally I want my test to ensure I am calling the web service correctly.

like image 510
Tom Avatar asked Feb 22 '16 16:02

Tom


1 Answers

You are mocking ws.DoSomethingAsync() but aren't setting it up to return anything. The DoThisAsync() method will fail because it will try to await null. You can fix this by changing your set up 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 above you can replace Task.FromResult(0) with Task.CompletedTask.

like image 182
Matt Cole Avatar answered Oct 07 '22 22:10

Matt Cole