Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq property with protected setter

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

like image 489
abatishchev Avatar asked Jan 26 '11 16:01

abatishchev


2 Answers

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

like image 188
Felice Pollano Avatar answered Oct 15 '22 09:10

Felice Pollano


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;
    }
}
like image 35
John Foster Avatar answered Oct 15 '22 10:10

John Foster