How to assign values to properties in moq?

时光毁灭记忆、已成空白 提交于 2019-11-28 05:12:53
Sunny Milenov

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 == "someone@example.com"); 

return mockUser;

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

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.

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