Reputation: 33
Recently I have gotten into unit testing my applications and have found myself at a bit of a difficult spot design wise in one of my classes.
I have a repository class which connects to the database, which looks a bit like this.
public interface Repository {
...
void register(Account account)
Account find(String email)
...
}
which, in implementation does this:
public class RepositoryImpl implements Repository {
...
public void register(Account account) {
if (find(account.getEmail() != null) return;
// Account with same email already exists.
...
}
}
This works fine in a live setting, but when unit testing it's a different story.
I use Mockito for mocking my dependencies, but I cant seem to mock the find
method in the implementation class.
So my first thought was to inject a Repository
in the register
method which I than can fake, but that seems a bit weird since I provide a method with a class which it is a member of itself.
After that I thought to just copy the find
logic to the register
method, but that violates the DRY principle.
So.. any ideas on solving this design problem? I guess it's a common problem since it's quite standard to have unique emails in a system.
Thanks!
Upvotes: 3
Views: 2054
Reputation: 26572
If you want to mock a method of the class under test you would need to spy it instead of using a concrete implementation:
// arrange
Account acc = new Account();
RepositoryImpl repoSpy = Mockito.spy(new RepositoryImpl());
doReturn(acc).when(repoSpy).find(Mockito.any(String.class));
//act
repoSpy.register(acc);
// assert ..
Thanks to that the register implementation will be used and the find method will be mocked to you liking.
Upvotes: 3