问题描述
如何强制使用AutoConfiguredMoqCustomization配置的AutoFixture自动模拟接口及其只读属性?
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;}
}
以及此类:
public class SomeClass {
public SomeClass(A dependency) {}
}
我想要的是将dependency
解析为一个模拟,该模拟将返回dependency.Property
中的某些内容:
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
推荐答案
这是由于Moq 4.2.1502.911中引入的一个错误所致,其中SetupAllProperties
覆盖了以前对仅获取属性所做的设置.
This is due to a bug introduced in Moq 4.2.1502.911, where SetupAllProperties
overrides previous setups done on get-only properties.
这是一个简单的复制:
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);
这是AutoFixture在后台创建Interface
实例的操作. Moq等于或大于4.2.1502.911的版本会失败,但是Moq的版本会通过.
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.
只需在Package Manager控制台上运行它即可
Simply run this on the Package Manager Console:
install-package Moq -version 4.2.1409.1722
此错误已在此处跟踪: https://github.com/Moq/moq4/issues/196
This bug is being tracked here: https://github.com/Moq/moq4/issues/196
这篇关于AutoConfiguredMoqCustomization和不可设置的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!