# 1.3.3 测试控制器

在对 HTML 页面的内容进行断言时，测试 web 应用程序可能比较棘手。幸运的是，Spring 提供了一些强大的测试支持，使测试 web 应用程序变得很容易。

就主页而言，你将编写一个与主页本身复杂度相当的测试。你的测试将对根路径 `/` 执行一个 HTTP GET 请求并期望得到一个成功的结果，其中视图名称为 home，结果内容包含短语 “Welcome to…”。程序清单 1.6 应该可以达到目的。

{% code title="程序清单 1.6 主页控制器测试" %}

```java
package tacos;
​
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
​
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
​
@RunWith(SpringRunner.class)
@WebMvcTest(HomeController.class)
public class HomeControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testHomePage() throws Exception {
        mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("home"))
            .andExpect(content().string(containsString("Welcome to...")));
    }
}
```

{% endcode %}

关于这个测试，你可能注意到的第一件事是，它与 `TacoCloudApplicationTests` 类在应用到它的注释方面略有不同。`HomeControllerTest` 使用 `@WebMvcTest` 注释，而不是 `@SpringBootTest` 标记。这是 Spring Boot 提供的一个特殊测试注释，它安排测试在 Spring MVC 应用程序的上下文中运行。更具体地说，在本例中，它安排 `HomeController` 在 Spring MVC 中注册，这样你就可以对它进行请求。

`@WebMvcTest` 还为测试 Spring MVC 提供了 Spring 支持。虽然可以让它启动服务器，但模拟 Spring MVC 的机制就足以满足你的目的了。测试类被注入了一个 `MockMvc` 对象中，以此用来测试来驱动模型。

`testHomePage()` 方法定义了要对主页执行的测试。它从 `MockMvc` 对象开始，执行针对 `/`（根路径）的 HTTP GET 请求。该请求规定了下列期望值：

* 响应应该有一个HTTP 200（OK）状态。
* 视图应该有一个合理的主页名称。
* 呈现的视图应该包含 “Welcome to...”

如果在 `MockMvc` 对象执行请求之后，这些期望中的任何一个都没有满足，那么测试就会失败。但是控制器和视图模板是为了满足这些期望而编写的，所以测试应该能够通过，或者至少能够通过一些表示测试通过的绿色提示。

控制器写好了，视图模板创建好了，测试通过了。看来你已经成功地实现了主页。但是，即使测试通过了，在浏览器中查看结果也会稍微让人更满意一些。毕竟，Taco Cloud 的客户也将这样看待它。让我们构建应用程序并运行它。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://potoyang.gitbook.io/spring-in-action-v5/di-1-zhang-spring-ru-men/1.3-bian-xie-spring-ying-yong-cheng-xu/1.3.3-ce-shi-kong-zhi-qi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
