user11081980
user11081980

Reputation: 3289

Mocking protected setters

My entity setters are all private so I use constructors to initialize my entities.

Now I need to write unit tests and I need to instantiate multiple objects. The "issue" is that I don't want to create constructors just to instantiate my entities with some random data. Instead, I would like to leverage C# easy way to do this:

var user = new User() { Name = "John", LastName = "Smith" };

One option I considered is to make the setters internal and set InternalsVisibleTo. But I don't want other entities to set these properties.

I don't think I can do this with Moq, though. Is there any other way to go around this?

Upvotes: 0

Views: 270

Answers (1)

Danny
Danny

Reputation: 541

If your goal is just to be able to Mock the protected properties you should be able to mock them if you make the getter public by doing:

public int A { get; protected set; }

Another option is to extend the class your trying to test and the test version of the class can have the constructors or public methods to set the properties.

Upvotes: 2

Related Questions