使用moq模拟虚拟只读属性

gkd*_*kdm 43 tdd unit-testing moq mocking

我找不到办法做到这一点,虽然这可以手工完成,所以为什么不用moq?

Mar*_*ann 80

鉴于这门课程

public abstract class MyAbstraction
{
    public virtual string Foo
    {
        get { return "foo"; }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样设置Foo(一个只读属性):

var stub = new Mock<MyAbstraction>();
stub.SetupGet(x => x.Foo).Returns("bar");
Run Code Online (Sandbox Code Playgroud)

stub.Object.Foo 现在将返回"bar"而不是"foo".

  • @l--''''''---------'''''''''''' 仅获取属性只是方法上的语法糖,所以如果您采用该语句就其逻辑结论而言,您可能会说最好不要使用返回数据的方法。我完全不同意这一点。 (2认同)