rjmurillo / moq.analyzers

Set of analyzers for Moq mocking library
BSD 3-Clause "New" or "Revised" License
22 stars 2 forks source link

Moq1201 incorrectly firing on new Moq versions #144

Closed rjmurillo closed 1 month ago

rjmurillo commented 4 months ago
public interface IFoo
{
  Task<bool> DoSomethingAsync();
}

var mock = new Mock<IFoo>();

// Preferred way 4.16+
mock.Setup(foo => foo.DoSomethingAsync().Result).Returns(true);

// Preferred way earlier than 4.16
mock.Setup(foo => foo.DoSomethingAsync()).ReturnsAsync(true);

From Moq Quickstart - Async Methods

There are several ways to set up "async" methods (e.g. methods returning a Task<T> or ValueTask<T>):

  • Starting with Moq 4.16, you can simply mock.Setup the returned task's .Result property. This works in nearly all setup and verification expressions:

    mock.Setup(foo => foo.DoSomethingAsync().Result).Returns(true);
  • In earlier versions, use setup helper methods like setup.ReturnsAsync, setup.ThrowsAsync where they are available:

    mock.Setup(foo => foo.DoSomethingAsync()).ReturnsAsync(true);