moq.analyzers icon indicating copy to clipboard operation
moq.analyzers copied to clipboard

Moq1201 incorrectly firing on new Moq versions

Open rjmurillo opened this issue 7 months ago • 0 comments

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);
    

rjmurillo avatar Jul 06 '24 20:07 rjmurillo