AutoConfiguredMoqCustomization and unsettable properties

笑着哭i 提交于 2019-12-08 17:38:24

问题


How do I force AutoFixture, that has been configured with AutoConfiguredMoqCustomization, to automatically mock interfaces and its read-only properties?

To make things clear, let's assume I have such an interface:

public interface A {
     int Property {get;}
}

and such class:

public class SomeClass {
     public SomeClass(A dependency) {}
}

What I want is to have dependency resolved to a mock that will return something in dependency.Property:

var fixture = new Fixture().Customize(new AutoConfiguredMoqCustomization());
var sut = fixture.Create<SomeClass>(); // <- dependency passed to SomeClass' constructor will have .Property returning null

回答1:


This is due to a bug introduced in Moq 4.2.1502.911, where SetupAllProperties overrides previous setups done on get-only properties.

Here's a simpler repro:

public interface Interface
{
    string Property { get; }
}

var a = new Mock<Interface>();

a.Setup(x => x.Property).Returns("test");
a.SetupAllProperties();

Assert.NotNull(a.Object.Property);

This is sort of what AutoFixture does behind the scenes to create an instance of Interface. This test fails with versions of Moq equal to or greater than 4.2.1502.911, but passes with lower versions.

Simply run this on the Package Manager Console:

install-package Moq -version 4.2.1409.1722

This bug is being tracked here: https://github.com/Moq/moq4/issues/196



来源:https://stackoverflow.com/questions/32067727/autoconfiguredmoqcustomization-and-unsettable-properties

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