2

I would like to create a customization that configures AutoFixture to pass types it DOES have implementations for off to Moq instead. How can I do that generically?

To clarify, consider:

    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);
    }

The test passes. AutoFixture has provided me with a dummy collection compatible with IDictionary. I would like the test to fail... specifically, I'd like to hand the IDictionary off to Moq and get something that doesn't complain about missing keys by default.

I'd like to use something like fixture.UseAutoMoq().ForceRelay<Dictionary<string,string>>().

I'm also open to better suggestions... but consider the test class sealed. I'm testing into code that uses this pattern a lot and I want a test convention around it.

cocogorilla
  • 1,815
  • 14
  • 36

1 Answers1

3

To do what you ask for, you can take the MockRelay added by AutoMoqCustomization and move it in front of the well-known-collections-builders:

[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
}

However, I don't think it's a good idea, as most of the .NET collection interfaces are big fat LSP violations, and there's no guarantee that auto-mocking them will produce meaningful behaviours - I'd expect the opposite to be the case.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • Thank you. The actual goal is to ignore the IDictionary altogether for the sake of other relevant dependencies that I do need mocked. If I don't, I have to inject an empty IDictionary implementation manually with Inject(dummyDictionary). That's a couple of lines of 'cruft' unrelated to the SUT in many tests. The underlying issue is that work is done in the constructor pertaining to the dictionary (keys called) that will be refactored out of the SUT constructor entirely... eventually. – cocogorilla Mar 06 '15 at 04:14