Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test afterPropertiesSet method in my spring application?

Tags:

java

junit

spring

I am working on writing some junit test for my spring application. Below is my application which implements InitializingBean interface,

public class InitializeFramework implements InitializingBean {


    @Override
    public void afterPropertiesSet() throws Exception {

        try {

        } catch (Exception e) {

        }
    }
}

Now I want to call afterPropertiesSet method from my junit test but somehow, I am not able to understand what is the right way to do this? I thought, I can use reflection to call this method but I don't think, it's a right way to do that?

Can anyone provide me a simple example for this on how to write a simple junit test that will test afterPropertiesSet method in InitializeFramework class?

like image 584
AKIWEB Avatar asked Sep 12 '13 18:09

AKIWEB


People also ask

How do I check my spring boot application?

For running the Spring Boot application, open the main application file, and run it as Java Application. When the application runs successfully, it shows the message in the console, as shown below. Now, open the browser and invoke the URL http://localhost:8080.


1 Answers

InitializingBean#afterProperties() without any ApplicationContext is just another method to implement and call manually.

@Test
public void afterPropertiesSet() {
    InitializeFramework framework = new InitializeFramework();
    framework.afterPropertiesSet();
    // the internals depend on the implementation
}

Spring's BeanFactory implementations will detect instances in the context that are of type InitializingBean and, after all the properties of the object have been set, call the afterPropertiesSet() method.

You can test that too by having your InitializeFramework bean be constructed by an ApplicationContext implementation.

Say you had

@Configuration
public class MyConfiguration {
    @Bean
    public InitializeFramework initializeFramework() {
        return new InitializeFramework();
    }
}

And somewhere in a test (not really junit worthy though, more of an integration test)

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);

When the context loads you will notice that the afterPropertiesSet() method of the InitializeFramework bean is called.

like image 184
Sotirios Delimanolis Avatar answered Oct 08 '22 15:10

Sotirios Delimanolis