Obecnie prowadzone testy, które wyglądać następująco:Jak korzystać MOQ przetestować kod, który wywołuje chronionych pomocników
// 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());
}
}
Powyższy wygląda dobrze dla prostych rzeczy, jednak klasa en dostaje wykładniczo większy i bardziej skomplikowany szybko . Chciałbym zastąpić klasę pośrednią za pomocą Moq. Jednak to się nie skompiluje, ponieważ z jakiegoś powodu nie mogę ustawić wartości zwracanej na chronionej metodzie.
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsFalse()
{
var mockClass = new Mock<ClassUnderTest>();
mockClass.Protected().Setup("HelperMethod").Returns(false);
Assert.IsFalse(mockClass.Object.MethodUnderTest());
}
Ktoś wie, jak to zrobię? Czy mogę to zrobić z moq?
Coś tu nie wygląda ... nie kpisz z SUT, kpisz z jego zależności. –
Tak, faktycznie Yojin kpi z SUT, aby zastąpić część SUT, która powinna być przechowywana osobno, a nie w chronionej metodzie pomocniczej. – Matthias