Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
Check calls Received() for async method

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

I found an answer here.

Received.InOrder(async () =>
{
    await _Commands.UpdateAsync(Arg.Is<Lobby>(l => l.Status == Status.Updated));
});
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!