nickdodd79 / AutoBogus

A C# library complementing the Bogus generator by adding auto creation and population capabilities.
MIT License
431 stars 50 forks source link

How to retrieve a mock from binder? #19

Closed lucasteles closed 5 years ago

lucasteles commented 5 years ago

We can use binders for Moq, FakeItEasy, etc to generate dependencies which are interfaces or abstract classes, but I don't find a way to get this mock back to setup it. That's is a way to do it?

nickdodd79 commented 5 years ago

Hi @lucasteles,

Unfortunately, the mocks generated by AutoBogus are not exposed to the consuming code. You can provide if yourself using the higher configuration level using the recently released Override feature:

var mock = new Mock<IInterface>();
AutoFaker.Generate<Item>(builder => builder.WithOverride<IInterface>(context => mock.Object));

Check out the documentation in the read me and let me know if you need any more help.

Nick.

lucasteles commented 5 years ago

@nickdodd79 Thanks, that's works, but I can't figure out the utility of the mock framework binders if I cant setup or verify then

I made it works using automocker container with a custom binder, but I wanted to make all this generator work with just Autobogus

Maybe I'm wanting more then what the lib proposes

nickdodd79 commented 5 years ago

Hey @lucasteles

You should be able to do all the generation using AutoBogus by using the override config. Here is a slightly more elaborate example using Moq that shows the setup and verification.

// OBJECTS
public interface ICalculator
{
  decimal Calculate();
}

public class Order
{
  private ICalculator _calculator;

  public Order(ICalculator calculator)
  {
    _calculator = calculator;
  }

  public string Id { get; set; }
  public decimal Total => _calculator.Calculate();
}

// TESTS
public void Should_Call_Mock_Method()
{
  // Arrange
  var total = AutoFaker.Generate<decimal>();
  var calculatorMock = new Mock<ICalculator>();

  calculatorMock.Setup(calculator => calculator.Calculate()).Returns(total);

  // Act
  var order = AutoFaker.Generate<Order>(builder =>
  {
    builder.WithOverride(context => calculatorMock.Object);
  });

  // Assert
  Assert.Equal(order.Total, total);

  calculatorMock.Verify(calculator => calculator.Calculate());
}
nickdodd79 commented 5 years ago

Closing as this seems to be resolved.