学习 Spring Boot 实战第5版:spring起步 课后作业
2021年1月27日大约 1 分钟
The best way to not feel hopeless is to get up and do something. Don't wait for good things to happen to you. If you go out and make some good things happen, you will fill the world with hope, you will fill yourself with hope. — Barack Obama
不管黑 pussy 、白 pussy,能够抓到老鼠就是好pussy
这里我将按照本节课要求,初始化一个名为 Pussy Cloud 的项目
运行一下PussyCloudApplicationTests,没有问题
编写Spring应用
添加控制器类
在com/pussycloud/core/web/
下新建一个HomeController.java
package com.pussycloud.core.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
* 主页的控制器类
* @author ZYJ
*/
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
添加视图
使用Thymeleaf模板定义视图home.html
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Pussy Cloud</title>
</head>
<body>
<h1>Welcome to ...</h1>
<!-- 相对与 resource 的路径-->
<img th:src="@{/images/PussyCloud.jpg}"/>
</body>
</html>
测试
编写测试类HomeControllerTest.java
package com.pussycloud.core.web;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
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.*;
@Slf4j
@WebMvcTest
public class HomeControllerTest {
@Autowired
private MockMvc mockMvc;
@BeforeEach
void setUp() {
log.info("HelloWorld!");
System.out.println("HelloWorld!");
}
@AfterEach
void tearDown() {
log.info("GoodByeWorld!");
System.out.println("GoodByeWorld!");
}
@Test
void home() {
}
@Test
public void testHomePage() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("home"))
.andExpect(content().string(containsString("Welcome to ...")));
}
}
PussyCloudApplicationTests.java
package com.pussycloud.core;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class PussyCloudApplicationTests {
@Test
void contextLoads() {
}
}
测试完成!