【发布时间】:2019-05-07 13:53:25
【问题描述】:
我正在尝试对公共类中的一些受保护方法进行单元测试。 我从这个类继承并通过从它返回超类的方法来测试继承的类。 我的示例代码如下:
基类:
public class A
{
// Private variables here
public A(){ }
protected virtual bool MethodOfA()
{
bool returnValue = false;
//some operation here to set returnValue
return returnValue;
}
protected bool AnotherMethodOfA()
{
bool anotherReturnValue = false;
bool operationCheck = MethodOfA();
if(operationCheck)
{
//do something to set the value of anotherReturnValue
}
return anotherReturnValue;
}
}
继承类:
public class B : A
{
// Private variables here
public B():base() { }
public new bool MethodOfA()
{
return base.MethodOfA();
}
public new bool AnotherMethodOfA()
{
var testMock = new Mock<A>();
//This is the part where I'm not sure how to get it to work.
testMock.CallBase = true; // I have tried it with and without this statement. couldn't get it to work
testMock.Protected()
.Setup<bool>("MethodOfA")
.Returns(true);
return base.AnotherMethodOfA();
}
}
测试:
public class TestB
{
private readonly B _sut
//some Mocks here for setup
public TestB()
{
_sut = new B();
}
[Fact]
public void AnotherMethodOfA_Test()
{
var result = _sut.AnotherMethodOfA();
Assert.True(result);
}
}
我需要的基本上是,当我从 TestB 类运行我的测试时,它会在需要调用 'MethodOfA()' 的方法中点击 '_sut.AnotherMethodOfA()',它应该只使用该值我在 Mock 中提供并继续执行,而不是调用实际方法(它现在正在执行)。
现在,如果我的 Method-Under-Test 更简单并且不在其中调用另一个方法,那么整个事情就会很简单(在我的许多其他方法中都是这种情况,我已经成功地测试了这些方法),但是由于此方法在执行过程中调用了另一个方法,因此我需要模拟此中间方法并将其传递给我的被测方法。
【问题讨论】:
-
你确定它没有因为你的设置错误而失败吗?您将其设置为返回 false
.Returns(false);而您的测试将其断言为true? -
我刚刚编辑了我的问题,以免混淆,但返回不会影响断言,因为它没有经过测试。 MethodOfA 是模拟,它应该返回 true(以前为 false)。这无关紧要,因为基于该返回值,被测试的方法 (AnotherMethodOfA()) 会执行一些操作,而这应该返回 true。
标签: c# unit-testing mocking moq access-modifiers