在pom文件中添加测试依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
复制粘贴自动创建的单元测试类
文件名改为HelloControllerTests
编写单元测试方法
@Autowired
private HelloController helloController;@Test
public void testHello() {String hello = helloController.hello();System.out.println(hello);Assert.isTrue("hello Spring Boot".equals(helloController.hello()), "helloController.hello()的返回值必须等于hello Spring Boot");}
使用MockMvc来做单元测试
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 cn.zptc.autoapp.demos.web.HelloController;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; @WebMvcTest(HelloController.class)
public class HelloControllerTest2 { @Autowired private MockMvc mockMvc; @Test public void whenGetGreeting_thenCorrectResponse() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello, World!")); }
}
这些测试通常运行得很快,因为它们不依赖于整个Spring应用程序的上下文启动。
它们专注于测试Controller的逻辑,而不需要启动整个服务器或数据库连接。
启动tomcat来做单元测试
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;import static org.assertj.core.api.Assertions.assertThat;@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerTest {@LocalServerPortprivate int port;@Autowiredprivate TestRestTemplate restTemplate;@Testpublic void testSayHello() {String url = "http://localhost:" + port + "/hello";String response = restTemplate.getForObject(url, String.class);assertThat(response).isEqualTo("Hello, World!");}
}
执行测试方法
光标定位到方法名称上,右键--》Run As --》JUnit Test。