我试图在类中模拟一个受保护的字段NodeIdGenerator
。我想在构造函数中设置字段的值,然后调用GetNext()
所属的方法NodeIdGenerator
。
我很确定我的测试没问题:
public class NodeIdGeneratorTests
{
[Fact(DisplayName = "Throws OverflowException when Int32.MaxValue " +
"IDs is exceeded")]
public void ThrowsOverflowExceptionWhenInt32MaxValueIdsIsExceeded()
{
var idGenerator = new NodeIdGeneratorMock(Int32.MaxValue);
Assert.Throws(typeof(OverflowException),
() => { idGenerator.GetNext(); });
}
/// <summary>
/// Mocks NodeIdGenerator to allow different starting values of
/// PreviousId.
/// </summary>
private class NodeIdGeneratorMock : NodeIdGenerator
{
private new int? _previousId;
public NodeIdGeneratorMock(int previousIds)
{
_previousId = previousIds;
}
}
}
我的问题是在模拟课上。当我GetNext()
在测试中调用时,它使用_previousId
属于超类的对象,而不是我希望它使用的对象(在模拟类中。)
那么,如何模拟受保护的字段?
PS:我已经阅读了这个问题,但我似乎无法理解它!