Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何模拟受保护的字段?_C#_Unit Testing_Mocking_Bdd_Xunit.net - Fatal编程技术网

C# 如何模拟受保护的字段?

C# 如何模拟受保护的字段?,c#,unit-testing,mocking,bdd,xunit.net,C#,Unit Testing,Mocking,Bdd,Xunit.net,我试图模拟类NodeIdGenerator中的受保护字段。我想在构造函数中设置字段的值,然后调用属于NodeIdGenerator的GetNext()方法 我很确定我的测试没问题: public class NodeIdGeneratorTests { [Fact(DisplayName = "Throws OverflowException when Int32.MaxValue " + "IDs is exceeded")] public void Thro

我试图模拟类
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;
        }
    }

}
公共类NodeIdGeneratorTests
{
[事实(DisplayName=“Int32.MaxValue时引发OverflowException”+
“超过ID”)]
public void ThrowsOverflowException当In32MaxValueIdIsExceped()时
{
var idGenerator=新节点IDGeneratorMock(Int32.MaxValue);
抛出(typeof(OverflowException),
()=>{idGenerator.GetNext();});
}
/// 
///模拟NodeIdGenerator以允许不同的
///以前的。
/// 
私有类NodeIdGeneratorMock:NodeIdGenerator
{
私有新int?\u以前的ID;
公共NodeIdGeneratorMock(int-previousId)
{
_previousId=previousId;
}
}
}
我的问题是在模拟课上。当我在测试中调用
GetNext()
时,它使用属于超类的
\u previousId
对象,而不是我希望它使用的对象(在模拟类中)

那么,如何模拟受保护字段?


附言:我已经读过了,但我似乎对它一无所知

如果可能,最好将
previousId
设置为虚拟属性,并覆盖模拟中的getter:

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

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

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


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

哈哈,太简单了。谢谢我刚刚删除了行
private new int_以前的