How to unit test code in the repository pattern?

孤街醉人 提交于 2019-12-13 04:02:25

问题


How to test this scenario:

I have a user repository that (so far) only has one method: SaveUser.
"SaveUser" is suposed to receive a user as a parameter and save it to the DB using EF 6.
If the user is new (new user is defined by a "Email" that is not present in the database) the method is supposed to insert it, if its not, the method is supposed to only update it.
Technically if this method is called, all business validation are OK, only remaining the act of actually persisting the user

My problem here is: I don't actually want to create a new user or update one every time... this would lead to undesired side effects in the future (let's call it "paper trail")... How do i do it?

Here is the test code:

public void CreateOrUpdateUserTest1()
    {
        UserDTO dto = new UserDTO();
        dto.UniqueId = new Guid("76BCB16B-4AD6-416B-BEF6-388D56217E76");
        dto.Name = "CreateOrUpdateUserTest1";
        dto.Email = "leo@leo.com";
        dto.Created = DateTime.Now;
        GeneralRepository repository = new GeneralRepository();
        //Now the user should be CREATED on the DB
        repository.SaveUser(dto);

        dto.Name = "CreateOrUpdateUserTest";
        //Now the user should be UPDATED on the DB
        repository.SaveUser(dto);
    }

回答1:


Your repository probably needs to invoke some methods of a third party library to actually persist the data. Unit-testing in such case could only make sense if you could mock the third party library and verify and the particular persistence methods are being correctly invoked by your repository. To achieve this, you need to refactor your code.

Otherwise, you can't unit-test this class, but also consider that maybe there is no need to. The third party library responsible for persistence is a different component, so testing if DB storage works correctly with your classes is rather a matter of Integration testing.



来源:https://stackoverflow.com/questions/20859777/how-to-unit-test-code-in-the-repository-pattern

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