How to test afterPropertiesSet method in my spring application?

14,358

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.

Share:
14,358

Related videos on Youtube

AKIWEB
Author by

AKIWEB

Updated on September 16, 2022

Comments

  • AKIWEB
    AKIWEB over 1 year

    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?

  • AKIWEB
    AKIWEB over 10 years
    Thanks Sotirios for the suggestion. That makes sense now to me.. Is there any way, you can provide an example for this statement You can test that too by having your InitializeFramework bean be constructed by an ApplicationContext implementation. I might also want to try out with this approach as well bcoz , I am passing certain properties from that xml file where bean is constructed..
  • Sotirios Delimanolis
    Sotirios Delimanolis over 10 years
    @TrekkieTechieT-T See my edit. Also, nothing prevents you from calling the afterPropertiesSet() yourself (and possibly cache the result).
  • Sotirios Delimanolis
    Sotirios Delimanolis over 10 years
    @TrekkieTechieT-T It might also help to understand what a FactoryBean is. Read its javadoc.