eureka19
eureka19

Reputation: 3060

Call @PostConstruct annotated method explicitly

I'm writing junit tests for one of my java class. I have a @PostConstruct annotated method as shown below for which I want to write the unit test:

@PostConstruct
public void initialize() {
    try {
        logger.info("Bootstrapping Safenet Initialization");
        String hello = cryptographicController.encrypt("Hello");
        logger.info("Bootstrapping Safenet " + hello);
    } catch (Throwable ex) {
        logger.error("Error initializing Crypto", ex);
        throw new DataConverterException();
    }
}

I want to write the unit test to test the DataConverterException. But i'm not sure if I can explicitly call the initialize method from my unit test.

How can I do this?

Upvotes: 1

Views: 2439

Answers (1)

Vinay Veluri
Vinay Veluri

Reputation: 6865

Case 1:

If the bean for the java class is created in xml and context configuration is loaded, then the bean life cycle method will be called automatically.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "XX")

Case 2:

Bean life cycle methods @PostConstruct and @PreDestroy should be called explicitly in the unit test cases to test.

If object of test class is created like below

JavaClass javaClass = new JavaClass();

then yes, as the bean is not created, then we need to call the initialize method explicilty.

both the cases will allow you to test the required area,

Mocking cryptographicController should give you the required options

@Test(expected=DataConverterException.class)
public void test() {
    doThrow(new RuntimeException()).when(cryptographicController).encrypt("Hello");
    javaClass.initialize();
}

Upvotes: 2

Related Questions