NullPointerException when using @Inject Annotation in JavaEE

When I test the createCitation method I always get a NullPointerException

You can’t simply test your application, because you delegated the responsibility of objects creation to the container which in unit tests (I assume you use it) does not exist.

public Citation createCitation(String quote) {
    Citation citation = new Citation();
    citation.setQuote(quote);
    citation.setWho(getName());
    repo.save(); // repo isn't initialized
    return citation;
}

If you want to test your code, mock repo object or use integration test.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top