Leonardo
Leonardo

Reputation: 11387

How to unit test code in the repository pattern?

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 = "[email protected]";
        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);
    }

Upvotes: 0

Views: 844

Answers (1)

BartoszKP
BartoszKP

Reputation: 35891

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.

Upvotes: 1

Related Questions