I always wondered how much I should test my code (with unit tests).
Let's say I have this component:
@Stateless
public class UserManager {
@PersistenceContext
EntityManager entityManager;
@Inject
Event<UserEvent> event;
public User getUserByUsername(String username) {
User user = entityManager
.createQuery("SELECT u FROM User u WHERE u.username = :username", User.class)
.setParameter("username", username)
.getSingleResult();
event.fire(new UserEvent("some message"));
return user;
}
}
To test it really thoroughly, I should mock Event and EntityManager. Which of these should I do then?
- Verify that method createQuery on entityManager is called exactly once with the given JPQL statement.
- Verify that method setParameter is called exactly once with the given parameters.
- Verify that method getSingleResult is called exactly once.
- Verify that event is fired with the given parameters exactly once.
- Test that the correct user is returned.
All? It seems to me very invasive since every little change in my implementation results in change needed to be done in my tests.
I have two a little different questions which I think are related.
Q2: On arquillian webiste, you can read this:
Arquillian let's you ditch the mocks and write real tests.
Does it mean I shouldn't use mock objects? How can (with arquillian) I test my code really thoroughly then?
Q3: According to TDD, you should write tests first and then the implementation. But how do you want to do it if you don't have either the implementation or the api, so the tests won't compile?