我目前運行測試,看起來像以下代碼:如何使用起訂量來測試要求受保護的助手
// 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());
}
任何人都知道我該怎麼做呢?我可以用moq來做這個嗎?
這裏有些東西似乎不對...你不嘲笑你的SUT,你嘲笑它的依賴。 –
是的,實際上Yojin嘲笑SUT來替換應該保持分開的SUT的一部分,而不是以受保護的輔助方法。 – Matthias