无法为Spring控制器的JUnit测试加载应用程序上下文

c86crjj0  于 2022-11-11  发布在  Spring
关注(0)|答案(7)|浏览(188)

我想写一个测试用例来检查我的控制器(getPersons)。这是一个服务器端代码。我搞不清楚我应该在@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/app-contest.xml"})里面放什么
第二,我得到了一些类似这样的错误:
无法加载应用程序上下文。找不到路径[我在@ContextConfiguration中指定的路径]
我有一个这样的结构:

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();
}

这是我的测试

@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());

}

追踪

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$1.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$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.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)

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

iqxoj9l9

iqxoj9l91#

正如讨论中提到的:WEB-INF实际上并不是类路径的一部分。如果使用公共模板,如maven,请使用src/main/resourcessrc/test/resourcesapp-context.xml放入。然后您可以使用classpath:
将您的配置文件放在src/main/resources/app-context.xml中,并使用以下代码:

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

您还可以使用不同的Bean配置来创建测试上下文。
将配置文件放入src/test/resources/test-app-context.xml并用途:

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

ny6fqffe2#

这个异常可能有多个根本原因。对我来说,我的mockMvc没有得到自动配置。我通过在类级别使用@WebMvcTest(MyController.class)解决了这个异常。这个注解将禁用完全自动配置,而只应用与MVC测试相关的配置。
另一种方法是,如果您希望加载完整的应用程序配置并使用MockMVC,则应该考虑将@SpringBootTest@AutoConfigureMockMvc结合使用,而不是将@WebMvcTest结合使用

hvvq6cgz

hvvq6cgz3#

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

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

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

yfjy0ee7

yfjy0ee74#

如果您根据标题来到这里,迫切需要一个解决方案,并且碰巧使用的是Junit5Jupiter,则需要使用

@ExtendWith(SpringExtension.class)

而不是

@RunWith(SpringJUnit4ClassRunner.class)
mo49yndu

mo49yndu5#

在Junit5中尝试以下操作:

@SpringBootTest(classes = {ServletWebServerFactoryAutoConfiguration.class},
        webEnvironment = RANDOM_PORT,
        properties = {"spring.cloud.config.enabled=false"})
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
nle07wnf

nle07wnf6#

使用相同版本的spring Boot 和spring cloud dependency对我很有效。

xmakbtuz

xmakbtuz7#

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

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

相关问题