给定一个Spring Boot + Thymeleaf Web应用程序(这与Spring项目的 gs-consuming-rest "initial" 代码树 几乎相同):
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── hello
│ │ ├── Application.java
│ │ ├── Config.java
│ │ └── Controller.java
│ └── resources
│ └── templates
│ └── index.html
└── test
└── java
└── hello
└── ControllerTest.java
...用户通过 http://localhost:8080/
得到了 "Hello, World!" 的问候,但是在集成测试中(ControllerTest.java
),Spring 的 "context" 配置似乎没有生效:
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