Spring @ContextConfiguration

天涯浪子 提交于 2019-12-04 03:16:52
ndrone

Try

@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" })

Honestly I would step away from the xml and go this route. Change

@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })

to

@ContextConfiguration(classes = { FloorServiceTestConfig.class })

And create the about class

@Configuration
public class FloorServiceTestConfig
{
    @Bean
    public FloorService floorService()
    {
          return new FloorService();
    }
}

This way when you need to mock your beans for class you're not testing it looks like below

@Configuration
public class FloorServiceTestConfig
{
    @Bean
    public FloorService floorService()
    {
          return Mockito.mock(FloorService.class);
    }
}
Shweta Gulati

The idea of @Configuration given above works nice. But for that you have to annotate your classes with @Configuration. This is not a nice idea when it comes to testing offline i.e when in your organisation test cases are not executed at built time. In that case going by @ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" }) will be a nice idea.

For using this method, take care of the following:

  1. Check your classpath in .classpath file of your project.

  2. If you cannot write the path of applicationContext relative to classpath.

You can have one more file as applicationContextTest folder kept in your test case folder and then one can use @ContextConfiguration(locations = { "classpath:applicationContextTest.xml"})

In your case you should use:

@ContextConfiguration(locations = "file:src/main/resources/META-INF/spring/applicationContext.xml")

Another hint, I see that you use your production applicationContext.xml in your test environment, IMHO it's not a good practice, try use a specific one for testing like applicationContext-test.xml, so you can play with your test context without hurting your production environment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!