Moq property with protected setter

房东的猫 提交于 2019-12-22 03:52:59

问题


I want to Moq next object:

abstract class Foo
{
    public string Bar { get; protected set; }
}

so that new Mock<Foo>().Bar return "Blah".

How can I do that?


fooMock.SetupGet<string>(s => s.Bar).Returns("Blah");

throws

Failure: System.NotSupportedException : Invalid setup on a non-virtual member: s => s.Date

and

fooMock.Protected().SetupGet<string>("Bar").Returns("Blah");

throws

To specify a setup for public property StatementSection.Date, use the typed overloads


回答1:


Since mocking is done by creating a proxy of your class,only virtual function/property can be "moqued"




回答2:


Like Felice (+1) said mocking creates a proxy which means you need to either make things virtual (so Moq can work its proxying magic and override the property).

As an alternative if you just want to squirt in a value you can manually stub the class you want to test and expose a means to get at the setter:-

public class FooStub : Foo {
    public SetBar(string newValue) {
       Bar = newValue;
    }
}


来源:https://stackoverflow.com/questions/4806909/moq-property-with-protected-setter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!