无法为 Spring 控制器的 JUnit 测试加载 ApplicationContext

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17220432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:02:21  来源:igfitidea点击:

Failed to load ApplicationContext for JUnit test of Spring controller

springspring-mvcjunitjunit4spring-mvc-test

提问by Saurabh

I want to write a test case to check my controller (getPersons). This is a server side code. I have confusion what should i put inside @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/app-contest.xml"})

我想编写一个测试用例来检查我的控制器(getPersons)。这是服务器端代码。我很困惑我应该在里面放什么@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/app-contest.xml"})

Secondly, I'm getting some errors like this:

其次,我收到了一些这样的错误:

Failed to load application context. Can not find the path [which I specified in @ContextConfiguration]

未能加载应用程序上下文。找不到路径 [我在@ContextConfiguration 中指定的]

I have a structure like this:

我有这样的结构:

 restAPI
    *src/main/java
      com.company.controller
         personController.java
    *Test
      com.company.testController
         personControllerTest.java
    *src
      main
       webapp
         WEBINF
           app-context.xml


@Autowired
private PersonService personService;

@RequestMapping(value="/t2/{yy_id}/person", method=RequestMethod.GET)
@ResponseBody
public PersonInfo[] getPersons() {

    return personService.getPersons();
}


This is my Test

这是我的测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:WEB-INF/app-context.xml"})
@WebAppConfiguration
public class PersonControllerTest  {


@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

@Autowired
private PersonService personService;

@Test
public void getPersons() throws Exception {

    this.mockMvc.perform(get("/t2/1/person")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());

}


Trace

痕迹

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:103)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:73)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:313)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}
0(ParentRunner.java:53) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [WEB-INF/application-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/application-context.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243) at org.springframework.test.context.web.GenericXmlWebContextLoader.loadBeanDefinitions(GenericXmlWebContextLoader.java:38) at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:113) at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:59) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248) at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124) at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148) ... 24 more Caused by: java.io.FileNotFoundException: class path resource [WEB-INF/app-context.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)

Can some one please help me out to figure it out what's wrong here?

有人可以帮我弄清楚这里出了什么问题吗?

回答by Martin Strejc

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

正如在 duscusion 中提到的:WEB-INF 并不是真正的类路径的一部分。如果使用maven等常用模板,使用src/main/resources或src/test/resources将app-context.xml放入。然后你可以使用“类路径:”。

Place your config file into src/main/resources/app-context.xml and use code

将您的配置文件放入 src/main/resources/app-context.xml 并使用代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

或者您可以使用不同的 bean 配置来测试上下文。

Place your config file into src/test/resources/test-app-context.xml and use code

将您的配置文件放入 src/test/resources/test-app-context.xml 并使用代码

<build>
    <testResources>
                <testResource>
                    <directory>src/main/webapp</directory>
                </testResource>
    </testResources>
</build>

回答by BharatB

If you are using Maven, add the below config in your pom.xml:

如果您使用 Maven,请在 pom.xml 中添加以下配置:

<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
</dependency>

With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.

使用此配置,您将能够访问 WEB-INF 文件夹中的 xml 文件。来自 Maven POM 参考: testResources 元素块包含 testResource 元素。它们的定义类似于资源元素,但在测试阶段自然会使用。

回答by mahesh chakravarthi

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class)at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

此异常可能有多个根本原因。对我来说,我的 mockMvc 没有被自动配置。我通过@WebMvcTest(MyController.class)在类级别使用解决了这个异常。此注释将禁用完全自动配置,而是仅应用与 MVC 测试相关的配置。

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTestcombined with @AutoConfigureMockMvcrather than @WebMvcTest

另一种方法是,如果您希望加载完整的应用程序配置并使用 MockMVC,则应考虑@SpringBootTest结合使用@AutoConfigureMockMvc而不是@WebMvcTest

回答by N.MATHIEU

Solved by adding the following dependency into pom.xml file :

通过在 pom.xml 文件中添加以下依赖项解决:

##代码##