我有这些接口(interface):
public interface IBase
{
int Value { get; }
}
public interface IDerived : IBase
{
new int Value { get; set; }
}
以下测试正常工作:
var mock = new Mock<IDerived>( MockBehavior.Strict );
mock.SetupGet( m => m.Value ).Returns( 0 );
IDerived o = mock.Object;
Assert.That( o.Value, Is.EqualTo( 0 ) );
但是,当我更改
o
的类型时至IBase
,我收到以下错误:Message: Moq.MockException : IBase.Value invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
这是设计使然吗?我需要删除
Strict
标志以访问基本接口(interface)属性(由派生接口(interface)隐藏)?还是有其他我可以使用的设置?作为旁注,有一个 issue处理基本/派生的只读/读写属性,但没有考虑模拟对象的声明类型。这可能是起订量的另一个问题吗?
最佳答案
Value
IBase
的属性(property)接口(interface)和IDerived
界面不一样。例如,您可以这样做:
public interface IBase
{
string Value { get; }
}
public interface IDerived : IBase
{
new string Value { get; }
}
public class Implementation : IDerived
{
string IBase.Value { get; } = "Base";
string IDerived.Value { get; } = "Derived";
}
模拟
IDerived
接口(interface)正确,您应该为这两个属性设置返回值。 Mock.As
方法在此处用于转换 IDerived
与 IBase
的接口(interface).Mock<IDerived> mock = new Mock<IDerived>( MockBehavior.Strict );
mock.Setup( obj => obj.Value ).Returns( "Derived" );
mock.As<IBase>().Setup( obj => obj.Value ).Returns( "Base" );
关于unit-testing - 模拟基接口(interface)属性不能通过派生接口(interface)的模拟工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338182/