如何模拟受保护的字段?
我正在尝试模拟类 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:我已阅读这个问题,但我似乎无法理解它!
I am attempting to mock a protected field in the class NodeIdGenerator
. I want to set the value of the field in a constructor an then call the GetNext()
method which belongs to NodeIdGenerator
.
Im pretty sure my test is OK:
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;
}
}
}
My problem is in the mock class. When I call GetNext()
in my test, it uses the _previousId
object belonging to the superclass, not the one which I want it to use (in the mock class.)
So, how do I mock the protected field?
PS: I have read this question but I can't seem to make head nor tail of it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您发布的代码将
_previousId
声明为new
,因此它隐藏了基类的字段 - 它不会覆盖它。当您调用GetNext
时,基类不会使用该值,它将使用自己的字段。尝试删除您的声明并仅访问基类的受保护字段。
The code you've posted declares
_previousId
asnew
, so it hides the base class' field - it doesn't override it. The base class won't use that value when you callGetNext
, it will use its own field.Try removing your declaration and just access the base class' protected field.
如果可能的话,最好将
previousId
设为虚拟属性并覆盖模拟中的 getter:If possible it would be better to make
previousId
a virtual property and override the getter in the mock: