简体   繁体   English

如何在类属性的模拟单元测试中设置默认值?

[英]How to set default value inside mock unit test for class property?

public MyClass 
{
    bool myflag ;
    bool detail ;
}

private async Task DemoAsync()
{
    MyClass myclassobj = new();
}
//But in test case I want to set default value for `myflag` and `detail` as `true` using mock I'm trying like below but getting error.

[TestMethod()]
public async Task Demotest()
{        
    bool someProperty = true;
    var mock = new Mock<MyClass>();
    mock.SetupSet(m => m.myflag = It.IsAny<bool>())
        .Callback<bool>(p => someProperty = p)
        .Verifiable();   
}

-> Error - Unsupported expression: m => m... The next member after the last one shown above is non-virtual, sealed, or not visible to the proxy factory. -> 错误 - 不支持的表达式:m => m... 上面显示的最后一个成员之后的下一个成员是非虚拟的、密封的或对代理工厂不可见。

You should make the myflag and detail properties virtual.您应该将myflagdetail属性设为虚拟。 This allows for the values to be overridden.这允许覆盖值。

public class MyClass 
{
    public virtual bool myflag { get; set; }
    public virtual bool detail { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM