Autofixture: How to express the following code declaratively?

China☆狼群 提交于 2019-12-10 19:18:48

问题


I am having trouble expressing the following code in a declarative fashion:

[Theory]
[InlineData(@"-o=C:\Temp\someFile -p=1")]
[InlineData(@"-p=1 -o=C:\Temp\someFile")]
public void ParseMissingParameterShouldReturnCorrectResult(
    string argsString
)
{
    .....
    var fixture = new Fixture();
    fixture.Register<IFoo>(fixture.Create<Foo>);
    fixture.Register<IBar>(fixture.Create<Bar>);

    var sut = fixture.Create<SomeClass>();
    .....
}

In my production code, I've got something like:

new SomeClass(new Foo(new Bar))

with the constructor of SomeClass being defined as:

public SomeClass(IFoo foo)

TIA,

David

EDIT:

SomeClass looks like

public class SomeClass : IQux
{
    private readonly IFoo _foo;

    public SomeClass(IFoo foo)
    {       
        _foo= foo;
    }

回答1:


You can declare the SUT (which is the SomeClass type) as a parameter on the test method:

[Theory]
[InlineAutoMockData(@"-o=C:\Temp\someFile -p=1")]
[InlineAutoMockData(@"-p=1 -o=C:\Temp\someFile")]
public void ParseMissingParameterShouldReturnCorrectResult(
    string argsString,
    SomeClass sut)
{
}

An easy way to create the [InlineAutoMockData] attribute is:

internal class InlineAutoMockDataAttribute : CompositeDataAttribute
{
    internal InlineAutoMockDataAttribute (params object[] values)
        : base(
            new InlineDataAttribute(values),
            new AutoDataAttribute(
                new Fixture().Customize(
                    new CompositeCustomization(
                        new AutoMoqCustomization()))))
    {
    }
}

Note:

If you also need to setup expectations on the IFoo or IBar mocked instances you can freeze them so that the same Frozen instances are passed in the SomeClass instance:

[Theory]
[InlineAutoMockData(@"-o=C:\Temp\someFile -p=1")]
[InlineAutoMockData(@"-p=1 -o=C:\Temp\someFile")]
public void ParseMissingParameterShouldReturnCorrectResult2(
    string argsString,
    [Frozen]Mock<IFoo> mock,
    [Frozen]Mock<IBar> stub,
    SomeClass sut)
{
}


来源:https://stackoverflow.com/questions/16145284/autofixture-how-to-express-the-following-code-declaratively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!