c# vs 2017 mocking var 属性 with return inside

c# vs 2017 mocking var property with return inside

我正在尝试在 class 中模拟一个自定义变量,它是只读的并且在 get 中有一个 return。

public class BaseController
{
    public string Local
    {
        return GlobalVariable.Local
    }
}

[TestMethod]
public void TestMethod()
{
    var baseControllerMock = Substitute.For<BaseController>();
    baseControllerMock.Local.Returns("local");
}

我的问题是,即使我在 return 内部使用 ReturnsForAnyArgs,我也厌倦了寻找全局变量并且它中断了,因为

System.NullReferenceException: 'Object reference not set to an instance of an object.' since the GlobalVariable is null.

我也试过模拟全局变量

[TestMethod]
public void TestMethod()
{
    var baseControllerMock = Substitute.For<BaseController>();
    var globalVarMock = Substitute.For<GlobalVariable>();
    globalVarMock.Local.returns("local");
    baseControllerMock.Local.Returns("local");
}

但是当它转到 return 时它说它仍然是空的。

尝试制作 BaseController.Locale virtual.

NSubstitute 只能与 overridable members of classes. If you add NSubstitute.Analyzers 一起用于您的测试项目,它将有助于检测无法在编译时替换的情况。


根据评论编辑: 这个测试对我来说没有错误地通过了:

    public static class GlobalVariable { public static string Local = "hi"; }
    public class BaseController
    {
        public virtual string Local { get { return GlobalVariable.Local; } }
    }
    [TestMethod]
    public void TestMethod() {
        var baseControllerMock = Substitute.For<BaseController>();
        baseControllerMock.Local.Returns("local");
    }