How to get AutoFlusture AutoMoq to return results from embedded services to an instance of an object?

I am trying to check a service class that uses the repository service. I have settings that I think should work with my repository service, but instead return anonymous results by default. If you look at the sample code below, I am trying to get the Foo objects that I registered in the settings class when I call the svc.GetFoos method, instead I get nothing:

void Main() { var fixture = new Fixture().Customize( new CompositeCustomization( new Customization(), new AutoMoqCustomization())); var svc = fixture.CreateAnonymous<Bar>(); Console.Write(svc.GetFoos().Count()); } // Define other methods and classes here public class Bar { public IQueryable<Foo> GetFoos() { return _rep.Query<Foo>(); } public Bar(IRepository rep) { _rep = rep; } private IRepository _rep; } public class Foo { public string Name {get;set;} } public class Customization : ICustomization { public void Customize(IFixture fixture) { var f = fixture .Build<Foo>() .With(x => x.Name, "FromCustomize") .CreateMany(2) .AsQueryable(); fixture.Register<IQueryable<Foo>>(() => f); } } public interface IRepository { IQueryable<T> Query<T>(); } 

If I add the following code to the Main method after creating the instance, it will work the way I want, but then I manually adjust my layouts and I'm not sure if AutoFixture AutoMoq gets me:

 var mock = fixture.Freeze<Mock<IRepository>>(); mock .Setup(x => x.Query<Foo>()) .Returns(fixture.CreateAnonymous<IQueryable<Foo>>); 

Thanks.

+4
source share
1 answer

AutoFixture.AutoMoq works like an Auto-Mocking Container . It will automatically graph the objects by injecting instances of Mock<T> into any user of the mentioned T

It cannot configure Mock<T> instances for you - after all, how to do it? Only you (the test writer) know what the appropriate interaction should be.

So, the code that you present, including the calls to Setup and Returns , is correct, although you might think about whether the Customization class is excessive.

If you need to automate many repetitive Moq settings, you should consider

  • Is the interface design and consumption pattern appropriate?
  • if fake is n't a better option than dynamic layout
+5
source

Source: https://habr.com/ru/post/1440644/


All Articles