RunWith SpringJUnit4ClassRunner gives error fail to load ApplicationContext with InitializingBean

488 Views Asked by At

I am using InitializingBean to initialise static properties in a modal class. This object I am auto wiring in a service

When I write a test case of service, I throws error: Failed to load ApplicationContext

Config class

public class AppConfig {
    private String prop1;

    protected void setProp1(String prop) {
        this.prop1 = prop;
    }

    public String getProp1() {
        return prop1;
    }
}

PropertyIntilizer class

public class PropertyIntializer implements InitializingBean {

    @Autowired
    private AppConfig appConfig;

    @Override
    public void afterPropertiesSet() throws Exception {

        appConfig.setProp1("PROP");
    }
}

Service Class

@Service
public class Service {

    @Autowired
    private AppConfig appConfig;

    public void doSomething(){
        System.out.println(appConfig.getProp1());
    }
}

TestClass

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class })
public class ServiceTest {

    @Autowired
    private Service service;

    @Test
    public void testService(){
        service.doSomething();
    }
}

This gives an error : Failed to load ApplicationContext

But when I remove Autowired AppConfig, it works

Edit: TestConfig class

@Configuration
@ComponentScan(basePackages = { "base.package" })
public class TestConfig {

}

my main classes are in base.package.main and test classes in base.package.test

1

There are 1 best solutions below

2
On

similar issue got resolved for me by adding JRE(thats comes with application server in my case websphere) in buid path