How to assign values to properties in moq?

I think you are missing purpose of mocking. Mocks used to mock dependencies of class you are testing:

enter image description here

System under test (SUT) should be tested in isolation (i.e. separate from other units). Otherwise errors in dependencies will cause your SUTs tests to fail. Also you should not write tests for mocks. That gives you nothing, because mocks are not production code. Mocks are not executed in your application.

So, you should mock CustomMembershipProvider only if you are testing some unit, which depends on it (BTW it's better to create some abstraction like interface ICustomMembershipProvider to depend on).

Or, if you are writing tests for CustomMembershipProvider class, then it should not be mocked - only dependencies of this provider should be mocked.


The way you prepare the mocked user is the problem.

moqUser.Object.Name = username;

will not set the name, unless you have setup the mock properly. Try this before assigning values to properties:

moqUser.SetupAllProperties();

This method will prepare all properties on the mock to be able to record the assigned value, and replay it later (i.e. to act as real property).

You can also use SetupProperty() method to set up individual properties to be able to record the passed in value.

Another approach is:

var mockUser = Mock.Of<User>( m =>
    m.Name == "whatever" &&
    m.Email == "[email protected]"); 

return mockUser;