1

我试图在类中模拟一个受保护的字段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:我已经阅读了这个问题,但我似乎无法理解它!

4

2 回答 2

1

如果可能的话,最好创建previousId一个虚拟属性并覆盖模拟中的 getter:

public class NodeIdGenerator
{
    protected virtual int? PreviousId { ... }
}

private class NodeIdGeneratorMock : NodeIdGenerator
{
    protected override int? PreviousId
    {
        get { return _previousId; }
    }
}
于 2010-11-22T21:21:52.460 回答
1

您发布的代码声明_previousIdnew,因此它隐藏了基类的字段 - 它不会覆盖它。调用时基类不会使用该值GetNext,它将使用自己的字段。

尝试删除您的声明并访问基类的受保护字段。

于 2010-11-22T21:23:21.110 回答