Search code examples
javacdijava-ee-8

NullPointerException when using @Inject Annotation in JavaEE


I have the following service class:

@Singleton
public class QuotesLoaderBean {

Properties quotes;
Properties names;
@Inject
public QuoteRepository repo;

public QuotesLoaderBean() {
}

@PostConstruct
public void init() {
    InputStream quotesInput = this.getClass().getClassLoader().getResourceAsStream("quotes.properties");
    InputStream namesInput = this.getClass().getClassLoader().getResourceAsStream("names.properties");

    quotes = new Properties();
    names = new Properties();
    try {
        quotes.load(quotesInput);
        names.load(namesInput);
    } catch (IOException ex) {
        Logger.getLogger(QuotesLoaderBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

public Citation getCitation() {
    Citation citation = new Citation();
    citation.setQuote(getQuote());
    citation.setWho(getName());
    return citation;
}

public String getQuote() {
    Enumeration keys = quotes.propertyNames();
    int elementNumber = new Random().nextInt(quotes.keySet().size());
    return quotes.getProperty(getElement(keys, elementNumber));
}

public String getName() {
    Enumeration keys = names.propertyNames();
    int elementNumber = new Random().nextInt(names.keySet().size());
    return names.getProperty(getElement(keys, elementNumber));
}

private String getElement(Enumeration keys, int elementNumber) {
    int i = 0;
    while (keys.hasMoreElements()) {
        if (i == elementNumber) {
            return (String) keys.nextElement();
        } else {
            i++;
            keys.nextElement();
        }
    }
    return null;
}
}

The Repository class is very simple for test purposes:

@Singleton
public class QuoteRepository {

public String save() {
    Gson gson = new GsonBuilder().create();
    return "Saved...";
}

}

When I test the createCitation method I always get a NullPointerException but I cant figure out why. Something is not working with Injection. I also have a api class that is annotated with @Stateless and there I can easily inject the service class with with the @Inject annotation.


Solution

  • 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.