为什么我的受保护方法没有返回我在模拟中设置的内容?运行单元测试时,受保护的方法返回 99,但我期望返回 1,因为我在模拟中设置了它。
[TestMethod]
public void TestMethod2()
{
var mock = new Mock<IMockTarget>();
mock.SetupGet(x => x.PropertyToMock).Returns("FixedValue");
mock.Protected()
.Setup<int>("MyProtectedGetIntMethod")
.Returns(1);
var sut = new ClassToTest();
var actualValue = sut.GetPrefixedValue(mock.Object);
Assert.AreEqual("Prefixed:FixedValue1", actualValue);
}
被测类
public class ClassToTest
{
public string GetPrefixedValue(IMockTarget provider)
{
var x = MyProtectedGetIntMethod();
return $"Prefixed:{provider.PropertyToMock}{x}";
}
protected int MyProtectedGetIntMethod() { return 99; }
}
public interface IMockTarget
{
string PropertyToMock { get; }
protected int MyProtectedGetIntMethod();
}
如果你想改变
ClassToTest.MyProtectedGetIntMethod
的行为,你应该模拟 ClassToTest
类:
var mock2 = new Mock<ClassToTest>();
mock2.Protected()
.Setup<int>("MyProtectedGetIntMethod")
.Returns(1);
var actualValue = mock2.Object.GetPrefixedValue(mock.Object);
MyProtectedGetIntMethod
方法也需要是虚拟的,模拟框架才能工作。
protected virtual int MyProtectedGetIntMethod() { return 99; }