强制中继到模拟框架

force relay to mocking framework

我想创建一个自定义,将 AutoFixture 配置为将它确实具有实现的类型传递给 Moq。一般我该怎么做?

为了澄清,请考虑:

    public class test
    {
        public string foo;
        public test(IDictionary<string, string> stuffing)
        {
            foo = stuffing["bogus"];
        }
    }

    [TestMethod]
    public void testInjection()
    {
        var fixture = new Fixture();
        bool didThrow;
        try
        {
            var sut = fixture.Create<test>();
            didThrow = false;
        }
        catch
        {
            didThrow = true;
        }
        Assert.IsTrue(didThrow);
    }

测试通过。 AutoFixture 为我提供了一个与 IDictionary 兼容的虚拟集合。我希望测试失败...具体来说,我想将 IDictionary 交给 Moq,并获得默认情况下不会抱怨丢失密钥的东西。

我想使用类似 fixture.UseAutoMoq().ForceRelay<Dictionary<string,string>>() 的东西。

我也乐于接受更好的建议...但请考虑将测试 class 密封。我正在测试大量使用这种模式的代码,我想要一个围绕它的测试约定。

要完成您的要求,您可以将 AutoMoqCustomization 添加的 MockRelay 移到众所周知的集合构建器前面:

[Fact]
public void PassByMovingAutoMoqRelay()
{
    var fixture = new Fixture().Customize(new AutoMoqCustomization());
    var relay = fixture.ResidueCollectors.OfType<MockRelay>().Single();
    fixture.Customizations.Add(relay);

    var sut = fixture.Create<MyClass>(); // Doesn't throw
}

但是,我认为这不是一个好主意,因为大多数 .NET 集合接口都是严重的 LSP 违规行为,并且不能保证自动模拟它们会产生有意义的行为 - 我希望情况恰恰相反。