AutoFixture/AutoMoq ignores injected instance/frozen mock

后端 未结 2 1975
自闭症患者
自闭症患者 2021-02-13 18:17

The short takeaway now that the solution has been found:

AutoFixture returns frozen the mock just fine; my sut that was also generated by AutoFixture ju

2条回答
  •  一整个雨季
    2021-02-13 18:47

    In the first test you can create an instance of the Fixture class with the AutoMoqCustomization applied:

    var fixture = new Fixture()
        .Customize(new AutoMoqCustomization());
    

    Then, the only changes are:

    Step 1

    // The following line:
    Mock settingsMock = new Mock();
    // Becomes:
    Mock settingsMock = fixture.Freeze>();
    

    Step 2

    // The following line:
    ITracingService tracing = new Mock().Object;
    // Becomes:
    ITracingService tracing = fixture.Freeze>().Object;
    

    Step 3

    // The following line:
    IMappingXml sut = new SettingMappingXml(settings, tracing);
    // Becomes:
    IMappingXml sut = fixture.CreateAnonymous();
    

    That's it!


    Here is how it works:

    Internally, Freeze creates an instance of the requested type (e.g. Mock) and then injects it so it will always return that instance when you request it again.

    This is what we do in Step 1 and Step 2.

    In Step 3 we request an instance of the SettingMappingXml type which depends on ISettings and ITracingService. Since we use Auto Mocking, the Fixture class will supply mocks for these interfaces. However, we have previously injected them with Freeze so the already created mocks are now automatically supplied.

提交回复
热议问题