1

I want to test the getCitation() method using jUnit:

@Singleton
public class QuotesLoaderBean {

Properties quotes;
Properties names;

@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());
    return citation;
}

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

In the Test File I want to Inject the Singleton and use it in the test method. But then I get the NullPointerException:

public class QuoteServiceTest {
@Inject
QuotesLoaderBean quotesLoaderBean;

public QuoteServiceTest() {
}

@BeforeClass
public static void setUpClass() {
}

@AfterClass
public static void tearDownClass() {
}

@Before
public void setUp() {
}

@After
public void tearDown() {
}

@Test
public void whenGetQuote_thenQuoteShouldBeReturned() {
    quotesLoaderBean.getQuote();
}

}

The test method is not finished, nut I just want to show the exception that occurs when I call a method from the Singleton. In another service class i can easily inject the class and call the methods.

softwareUser
  • 398
  • 2
  • 6
  • 21

1 Answers1

0

Injection is handled by a DI-enabled container in execution time. When you deploy your entire application, a container is set and injection works fine. When executing unit tests, none of the services are launched, and any @Inject will end up with the variable set to null, because no container will be launched either.

So, in order to test your code, you may want to build the service inside setUp method:

public class QuotesServiceTest {

    QuotesLoaderBean quotesLoaderBean;

// ...
    @Before
    public void setUp() {
        quotesLoaderBean = new QuotesLoaderBean();
        // call init method after construction
        quotesLoaderBean.init();
    }
// ...
}


Nowhere Man
  • 19,170
  • 9
  • 17
  • 42