Search code examples
c#genericsmoqautofixtureautomoq

Autofixture.Automoq - generics make bool always true


public interface IResult
{
    bool Success { get; } 
}

public interface IResult<T> : IResult
{

}

Using AutoFixure, and AutoMoq I am trying to find a way to to make Success always true, no matter what type T is. Registering a fake is easy enough with IResult, but that doesn't seem to work for IResult<T>


Solution

  • Using a fake implementation

    public class FakeResult<T> : IResult<T> {
        public bool Success {
            get { return true; }
        }
    }
    

    along with adding a TypeRelay customization

     fixture.Customizations.Add(new TypeRelay(typeof(IResult<>), typeof(FakeResult<>)));
    

    All calls for IResult<> will use the FakeResult<> which has its Success to return trueno matter what is the type of T.

    Full example to test that the mock works as intended.

    [TestClass]
    public class AutoFixtureDefaultGeneric {
        [TestMethod]
        public void AutoFixture_Should_Create_Generic_With_Default() {
            // Arrange
            Fixture fixture = new Fixture();
            fixture.Customizations.Add(new TypeRelay(typeof(IResult<>), typeof(FakeResult<>)));
    
            //Act
            var result = fixture.Create<IResult<string>>();
    
            //Assert
            result.Success.Should().BeTrue();
        }
    }