模拟基接口属性不适用于派生接口的模拟
Mocking base interface properties does not work through a mock of a derived 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
标志才能访问基接口 属性(被派生接口隐藏)?或者我可以使用其他类型的设置吗?
作为旁注,有一个 issue 处理 base/derived read-only/read-write 属性,但那里没有考虑模拟对象的声明类型。这可能是 Moq 中的另一个问题吗?
IBase
界面和IDerived
界面的Value
属性不一样。例如,您可以这样做:
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
接口,您应该为这两个属性设置 return 值。 Mock.As
方法在这里很有用,可以将 IDerived
接口转换为 IBase
.
Mock<IDerived> mock = new Mock<IDerived>( MockBehavior.Strict );
mock.Setup( obj => obj.Value ).Returns( "Derived" );
mock.As<IBase>().Setup( obj => obj.Value ).Returns( "Base" );
我有这些接口:
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
标志才能访问基接口 属性(被派生接口隐藏)?或者我可以使用其他类型的设置吗?
作为旁注,有一个 issue 处理 base/derived read-only/read-write 属性,但那里没有考虑模拟对象的声明类型。这可能是 Moq 中的另一个问题吗?
IBase
界面和IDerived
界面的Value
属性不一样。例如,您可以这样做:
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
接口,您应该为这两个属性设置 return 值。 Mock.As
方法在这里很有用,可以将 IDerived
接口转换为 IBase
.
Mock<IDerived> mock = new Mock<IDerived>( MockBehavior.Strict );
mock.Setup( obj => obj.Value ).Returns( "Derived" );
mock.As<IBase>().Setup( obj => obj.Value ).Returns( "Base" );