拥有受保护的二传手的Moq财产

aba*_*hev 10 .net c# unit-testing moq mocking

我想要Moq下一个对象:

abstract class Foo
{
    public string Bar { get; protected set; }
}
Run Code Online (Sandbox Code Playgroud)

所以new Mock<Foo>().Bar回归"Blah".

我怎样才能做到这一点?


fooMock.SetupGet<string>(s => s.Bar).Returns("Blah");
Run Code Online (Sandbox Code Playgroud)

失败:System.NotSupportedException:非虚拟成员上的设置无效:s => s.Date

fooMock.Protected().SetupGet<string>("Bar").Returns("Blah");
Run Code Online (Sandbox Code Playgroud)

要指定公共属性StatementSection.Date的设置,请使用类型化重载

Joh*_*ter 9

就像Felice(+1)所说的那样,模拟创建了一个代理,这意味着你需要让事物变得虚拟(因此Moq可以使用它的代理魔法并覆盖属性).

作为替代方案,如果您只想喷射一个值,您可以手动存根您想要测试的类并公开获取setter的方法: -

public class FooStub : Foo {
    public SetBar(string newValue) {
       Bar = newValue;
    }
}
Run Code Online (Sandbox Code Playgroud)


Fel*_*ano 8

由于模拟是通过创建类的代理来完成的,因此只有虚拟函数/属性可以"moqued"