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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With