0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the second option, just create a TestUser that derives from User and add public setters there that call protected setters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.