The Right Way
You would not be testing the method checkUsername
directly, you should be testing it indirectly by testing your create
method.
You have 3 tests from what I can see that you need to create:
- Test the outcome when username is
dummy
- you want to be testing for the expected exception of UsernameUnavailableException
with the message of Username = 'dummy' is cannot be used!
.
- Test the outcome is
UsernameIsInUseException
when a username already exists and the expected exception error message is Username = '<insert username>' is being used by another user!
.
- Test what actually happens when the user is successfully saved.
If this was me I would be looking at creating a mocked/spied version of userRepository
so I could manipulate the response for both existsByUsername
and save
for each individual test. I would also assert how many times those methods get called for each test, for example for test (1) I would not expect either existsByUsername
or save
to be called so I would verify that it was called 0 times. Whereas for test (2) I would expect existsByUsername
to be called at least once and save
to be called 0 times; and for test (3) I would expect both methods to be called at least once and only once.
If you cannot test a private method indirectly then it most likely falls into one of 3 categories:
- The private method is dead code because it cannot be indirectly accessed.
- Your code has been poorly designed and you should consider refactoring to be more efficient.
- The method you are trying to test should never have been private in the first place, does it make sense from a design point of view to make it public?
The Wrong Way
The wrong way would be to use reflection to access that private method, unfortunately I know people who swear by this method but in my opinion it is the wrong way to carry out tests of a private method; and unfortunately I have used reflection myself to test a private method within a legacy project in which I was unable to refactor so would have fallen into category 2 above.
The snippet below is from a book called JUnit In Action
, I would recommend picking up a copy if you can.
Using reflection to access private properties and methods breaks what
we learn as a good student and well disciplined developer, and that is
the object-oriented language is built around 3 pillars: encapsulation,
inheritance and polymorphism
I have not shared code because this is clearly a homework question, however above should be enough to help guide you towards achieving what you need.