Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a method which uses another method from the same class

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!

like image 962
CPN Avatar asked Mar 18 '26 01:03

CPN


1 Answers

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.

like image 195
Maciej Kowalski Avatar answered Mar 20 '26 13:03

Maciej Kowalski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!