How to use AutoFixture in this case?

心不动则不痛 提交于 2019-12-06 10:49:02
Nikos Baxevanis

Note: I couldn't compile the test you provided.. however it seems that all you have to do is:

fixture.Inject(mockRepositoryFactory);

You may try the following:

[Fact]
public void TestWithAutoFixtureImperatively()
{
    // Fixture setup
    var fixture = new Fixture()
        .Customize(new AutoFakeItEasyCustomization());

    var expectedRecord = fixture.Create<string>();
    var boundArgOption = fixture.Create<BoundArgumentOption>();

    var repositoryStub = A.Fake<IRepository>();
    A.CallTo(() => 
        repositoryStub
            .Get(boundArgOption))
            .Returns(expectedRecord);

    var repositoryFactoryStub = A.Fake<IRepositoryFactory>();
    A.CallTo(() => 
        repositoryFactoryStub
            .Create(boundArgOption))
            .Returns(repositoryStub);

    fixture.Inject(repositoryFactoryStub);

    var sut = fixture.Create<HtmlOutputBuilder>();

    // Exercise system
    string result = sut.BuildReport(boundArgOption);

    // Verify outcome
    result.Should().Be(expectedRecord);

    // Teardown
}

We inject the IRepositoryFactory so that the same, injected, instance will be passed in the SUT.


Alternatively, you can also use AutoFixture declaratively with the xUnit.net extension:

[Theory, AutoDomainData]
public void TestWithAutoFixtureDeclaratively(
    string expectedRecord,
    BoundArgumentOption boundArgOption,
    Fake<IRepository> repositoryStub,
    [Frozen]Fake<IRepositoryFactory> repositoryFactoryStub,
    HtmlOutputBuilder sut)
{
    // Fixture setup
    A.CallTo(() =>
        repositoryStub
            .FakedObject
            .Get(boundArgOption))
            .Returns(expectedRecord);

    A.CallTo(() =>
        repositoryFactoryStub
            .FakedObject
            .Create(boundArgOption))
            .Returns(repositoryStub.FakedObject);

    // Exercise system
    string result = sut.BuildReport(boundArgOption);

    // Verify outcome
    result.Should().Be(expectedRecord);

    // Teardown
} 

The AutoDomainDataAttribute is defined as:

internal class AutoDomainDataAttribute : CompositeDataAttribute
{
    internal AutoDomainDataAttribute()
        : base(
            new AutoDataAttribute(
                new Fixture().Customize(
                    new AutoFakeItEasyCustomization())))
    {
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!