【发布时间】:2016-04-08 23:41:24
【问题描述】:
给定一个 Spring Boot + Thymeleaf Web 应用程序(这与 Spring 项目的 gs-consuming-rest "initial" code tree 几乎相同):
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── hello
│ │ ├── Application.java
│ │ ├── Config.java
│ │ └── Controller.java
│ └── resources
│ └── templates
│ └── index.html
└── test
└── java
└── hello
└── ControllerTest.java
...用户会收到“Hello World!”的问候。 http://localhost:8080/,但 Spring 的“上下文”的布线似乎不适用于集成测试 (ControllerTest.java):
java.lang.AssertionError: Status
Expected :200
Actual :404
测试中的项目布局和/或配置注释有什么问题?
src/main/webapp/ 以及 web.xml 和 WEB-INF/ 之类的东西是故意丢失的。这里的目标是使用最少的配置,通过集成测试来测试应用程序的视图和控制器的开发。
下面的血腥细节。提前为“文字墙”道歉。
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
Application.java
package hello;
// ...
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Throwable {
SpringApplication.run(Application.class, args);
}
}
Controller.java
package hello;
@org.springframework.stereotype.Controller
public class Controller {
}
Config.java
package hello;
// ...
@Configuration
public class Config extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
}
ControllerTest.java
package hello;
// ...
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = Config.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void test() throws Exception {
this.mockMvc
.perform(get("/"))
.andExpect(status().isOk());
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<p>Hello world!</p>
</body>
</html>
【问题讨论】:
-
您不应该使用
@ContextConfiguration,而是使用@ SpringApplicationConfiguration,并将其指向您的应用程序类而不是配置类。 -
@M.Deinum 我使用@SpringApplicationConfiguration。如何使用不同的 @Configuration 类进行测试?
标签: java spring spring-boot integration-testing thymeleaf