1. @SpringBootTest 單元測試
1. 添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2. 添加測試類
package com.test.spring_boot_demo;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) // 底層用junit SpringJUnit4ClassRunner
@SpringBootTest(classes = {SdSpringBootApplication.class}) // 啓動整個SpringBoot工具
public class SpringBootDemoTest {
@Test
public void testOne() {
System.out.println("test hello 1");
TestCase.assertEquals(1, 1);
}
@Test
public void testTwo() {
System.out.println("test hello 2");
TestCase.assertEquals(1, 1);
}
@Before
public void testBefore() {
System.out.println("before");
}
@After
public void testAfter() {
System.out.println("after");
}
}
3. 運行測試
- 如果測試某個方法,直接運行要測試的方法。
- 如果測試類中的多個方法,直接運行測試類。
2. MocMvc(模擬MVC請求,實現接口測試)
1. 添加測試接口(Controller)
@GetMapping("/test/home")
public String testHome() {
return "test home ...";
}
2. 添加測試類
package com.test.spring_boot_demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SdSpringBootApplication.class})
@AutoConfigureMockMvc
public class MockMvcDemoTest {
@Autowired
private MockMvc mockMvc;
@Test
public void apiTest() throws Exception {
// perform: 執行一個 RequestBuilder 請求
// andExpect: 添加 ResultMatcher -> MockMvcResultMatchers 驗證規則
// andReturn: 最後返回相應的 MvcResult
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/home")).
andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
int status = mvcResult.getResponse().getStatus();
System.out.println(status);
}
}