【发布时间】:2010-11-22 21:10:15
【问题描述】:
我正在尝试模拟 NodeIdGenerator 类中的受保护字段。我想在构造函数中设置字段的值,然后调用属于NodeIdGenerator的GetNext()方法。
我很确定我的测试没问题:
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:我已经阅读了this question,但我似乎无法理解它!
【问题讨论】:
标签: c# unit-testing mocking bdd xunit.net