When I run the following code:
[Test]
public async Task Can_Test_Update()
{
var response = await _controller.UpdateAsync(Guid.NewGuid());
response.Valid.Should().BeTrue();
_commands.Received().UpdateAsync(
Arg.Is<Something>(
l => l.Status == Status.Updated));
}
If I add "await" preceding the "_commands.Received().UpdateAsync", it throws a null reference exception. How can I stop this happening, or is await not necessary?
When NSubstitute sees an async call it automatically creates a completed task so the await works as you would expect in your code (and not throw a NullReferenceException). In this case that would be the task returned from _commands.UpdateAsync(Status.Updated)) inside the method you are testing.
The .Received() call on the other hand is verifying that the async method was called, that is fully synchronous so it doesn't need to be awaited.
The key thing to remember is that async methods return a Task. Calling the async method and returning the task is fully synchronous, you then await the Task to know when the asyncronous operation which the task represents is completed.
According to this answer on Stack Overflow, as of NSubstitute version 1.8.3 you can use await and it will work as expected, rather than throwing a NullReferenceException.
I've just tried it out as I was on version 1.5.0 and getting the NullReferenceException as you describe, but now I'm on the latest (1.10.0), it's working well.