【发布时间】:2011-12-12 16:39:56
【问题描述】:
我目前运行的测试如下所示:
// In Blah.cs
public class ClassUnderTest
{
public bool MethodUnderTest()
{
// Do a bunch of stuff...
return HelperMethod();
}
protected virtual bool HelperMethod()
{
bool success = false;
// Proprietary Hardware Access.
// Database Calls.
// File System Modifications.
return success;
}
}
// In TestBlah.cs
public class TestStub : ClassUnderTest
{
public bool HelperMethodReturnValue;
protected override bool HelperMethod()
{
return HelperMethodReturnValue;
}
}
[TestClass]
public class TestingClass
{
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsTrue()
{
var stub = new TestStub();
stub.HelperMethodReturnValue = true;
Assert.IsTrue(stub.MethodUnderTest());
}
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsFalse()
{
var stub = new TestStub();
stub.HelperMethodReturnValue = false;
Assert.IsFalse(stub.MethodUnderTest());
}
}
上面的内容对于简单的事情看起来不错,但是存根类会迅速变得更大和更复杂。 我想使用 Moq 替换存根类。但是这不会编译,因为由于某种原因我无法在受保护的方法上设置返回值。
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsFalse()
{
var mockClass = new Mock<ClassUnderTest>();
mockClass.Protected().Setup("HelperMethod").Returns(false);
Assert.IsFalse(mockClass.Object.MethodUnderTest());
}
有人知道我会怎么做吗?我可以用最小起订量做到这一点吗?
【问题讨论】:
-
这里似乎有些不对劲......你没有模拟你的 SUT,你模拟了它的依赖关系。
-
是的,实际上 Yojin 模拟了 SUT 以替换 SUT 中应该分开的部分,而不是在受保护的辅助方法中。
标签: c# unit-testing moq