2010-11-22 50 views
1

我试图模拟NodeIdGenerator类中的受保护字段。我想在一个构造函数中设置字段的值,然后调用属于NodeIdGeneratorGetNext()方法。如何模拟受保护的字段?

Im相当肯定我的测试是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; 
     } 
    } 

} 

我的问题是在模拟类。当我在我的测试呼叫GetNext(),它使用属于超,不,我想它使用一个_previousId对象(在模拟类。)

所以,我怎么嘲笑保护现场?

PS:我已阅读this question,但我似乎无法使头部和尾巴!

回答

1

你已经发布的代码声明_previousIdnew,所以它隐藏了基类字段 - 它不覆盖它。当您拨打GetNext时,基类将不会使用该值,它将使用自己的字段。

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

+0

哈哈,那么容易。谢谢。我刚刚删除了行'private new int? _previousId;`和嘿presto! – Nobody 2010-11-22 21:28:47

1

如果可能的话这将是更好地使previousId虚拟财产,并覆盖了模拟,吸气:

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

private class NodeIdGeneratorMock : NodeIdGenerator 
{ 
    protected override int? PreviousId 
    { 
     get { return _previousId; } 
    } 
} 
相关问题