AutoFixture构建 - 冻结 - 创建序列

时间:2017-06-12 15:39:05

标签: c# unit-testing moq autofixture

我刚刚注意到,每当我在Freeze - Build<>()之间进行Create()次调用Freeze时,var fixture = new Fixture().Customize(new AutoMoqCustomization()) var builder = fixture.Build<SomeType>(); fixture.Freeze<Mock<ISomeInterface>>().Setup(m => m.SomeProperty).Returns(10); var sut = builder.Create(); // if SomeType uses ISomeInterface.SomeProperty it will get 0 returned - *incorrect* 的调用都不会被应用。它是AutoFixture的行为还是bug?

说清楚:

var fixture = new Fixture().Customize(new AutoMoqCustomization())
fixture.Freeze<Mock<ISomeInterface>>().Setup(m => m.SomeProperty).Returns(10);
var sut = fixture.Create<SomeType>();
// if SomeType uses ISomeInterface.SomeProperty it will get 10 returned - correct

这很好用:

writeEntryToLogFile()

2 个答案:

答案 0 :(得分:1)

如果在调用构建器之前冻结它将起作用

冻结 - 构建 - 创建序列

[TestClass]
public class AutoFixtureTests {
    [TestMethod]
    public void _FreezeBuildCreate() {
        //Arrange
        var expected = 10;
        var fixture = new Fixture().Customize(new AutoMoqCustomization());
        fixture.Freeze<Mock<ISomeInterface>>().Setup(m => m.SomeProperty).Returns(expected);
        var builder = fixture.Build<SomeType>();
        var sut = builder.Create();

        //Act
        var actual = sut.GetA();

        //Assert
        Assert.AreEqual(expected, actual);
    }

    public class SomeType {
        private ISomeInterface a;
        public SomeType(ISomeInterface a) {
            this.a = a;
        }
        public int GetA() {
            return a.SomeProperty;
        }
    }

    public interface ISomeInterface {
        int SomeProperty { get; set; }
    }
}

如果你看一下Build方法的定义

  

有效地自定义单个对象的创建算法   关闭Ploeh.AutoFixture.IFixture上的所有自定义。

如果在冻结之前调用build,则之后的所有自定义都不会生效。

答案 1 :(得分:1)

所以这就是我自己解决这个问题的方法。由于我在选择Build - Create的位置时没有太多选择,因此必须使用事件。哦,我不想让Create虚拟。

这是一些伪代码:

public class BaseSutBuilder<TSut> {
    // other weird stuff...

    // somewhere in ctor:
    protected BaseSutBuilder() {
        SutBuilders = _ => {};
    }

    protected Action<ICustomizationComposer<TSut>> SutBuilders { get; }

    public TSut Create() {
        var builder = _fixture.Build<TSut>();
        SutBuilders(builder);
        return builder.Create();
    }
}

public class SomeTypeSutBuilder: BaseSutBuilder<SomeType> {
    public SomeTypeSutBuilder() {
        SutBuilders += c => c.With(.......
        SutBuilders += c => c.With(.......
    }
}