Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture.AutoMoq: set value to read only property

I use AutoFixture with AutoMoq. I try to create a fake instance of a class which has a property with a getter but without a setter. I expect AutoFixture to configure the mock so it will return the given value even there is no setter.

My code is something like that:

var data = new List<Data>() { new Data() };
var userManager = fixture.Build<IRepository>()
      //.With(x => x.Data, data)
        .CreateAnonymous();
Mock.Get(userManager).Setup(x => x.Data).Returns(data);

Unfortunately, the "With" method does not work in this case because auto fixture says that Data does not have any setter which why I have to set the value afterwards with a direct call to the mock.

Is there a way that auto fixture can do this by its own so I do not need the last line of code?

Edit: I made a mistake, the code example does not work. It should be

var data = new List<Data>() { new Data() };
var userManager = fixture.CreateAnonymous<IRepository>();
Mock.Get(userManager).Setup(x => x.Data).Returns(data)

Nevertheless, it would be good if there would be a with method for fake instance.

like image 514
HerrLoesch Avatar asked Mar 11 '13 12:03

HerrLoesch


1 Answers

AutoFixture.AutoMoq doesn't set up your Test Doubles for you.

If you want to avoid having to specify a setup for IRepository.Data in each and every test case, you can package the setup in a Customization.

public class RepositoryCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Register(() =>
        {
            var td = new Mock<IRepository>();
            td.SetupGet(r => r.Data).Returns(fixture.CreateMany<Data>());
            return td.Object;
        });
    }
}

With that, the following test passes:

[Fact]
public void AutoProperty()
{
    var fixture = new Fixture().Customize(new RepositoryCustomization());
    var repo = fixture.Create<IRepository>();
    Assert.NotEmpty(repo.Data);
}

In theory it would be possible to write automated code that reflects over the members of an interface and sets up a return value for each member, but IMO, this should never be default behaviour for AutoFixture.AutoMoq.

like image 78
Mark Seemann Avatar answered Nov 13 '22 11:11

Mark Seemann