How do I set up methods on mocks to return null by default?

1.2k views Asked by At

I am using AutoFixture with AutoMoq to mock my dependencies in a unit test like this

public class MyObject
{
   public string Value { get; set; }
}

public interface IMyService
{
   MyObject GetMyObject();
}

public class Tests
{
   [Fact]
   public void MyTest()
   {
      var fixture = new Fixture().Customize(new AutoMoqCustomization());
      var myService = fixture.Create<Mock<IMyService>>();

      // I want myObject to be null, but I'm getting a Mock<MyObject> instead
      var myObject = myService.Object.GetMyObject();    ​
   ​}
}

I want the line var myObject = myService.Object.GetMyObject(); to return null, but instead it returns a Mock<MyObject> value. I known I can do myService.Setup(e => e.GetMyObject()).Returns((MyObject)null); to explicitly tell it to return null, but I have a number of methods like that being called throughout my tests and I want them to return null by default, without me having to explicitly call Setup on them.

Is there a way to set up the fixture to have all methods on the mock return null by default?

1

There are 1 answers

0
Andrei Ivascu On BEST ANSWER

The suggestion from the comments was close. The part that was missing is setting the CofnigureMembers property on AutoMoqCustomization to true so that AutoFixture can resolve the instances of the members.

[Fact]
public void MyTest()
{
    var fixture = new Fixture().Customize(new AutoMoqCustomization
    {
        ConfigureMembers = true,
    });
    fixture.Inject<MyObject>(null));
    var myService = fixture.Create<Mock<IMyService>>();

    var myObject = myService.Object.GetMyObject();
    
    Assert.Null(myObject);
}