單元測試Case
單元測試1:
@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerApplicationTest {
@Autowired
private MockMvc mvc;
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Spring Boot!")));
}
}
單元測試2:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Spring Boot!")));
}
}
單元測試3:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/");
}
@Test
public void getHello() throws Exception {
ResponseEntity<String> response = template.getForEntity(base.toString(),
String.class);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}
這三個測試用例實現類似的功能,但是它們之間有什麼區別呢?
區別與分析
第一個是僅僅掃描Controller的代碼進行執行,如果Controller中有相關依賴則需要Mock,並進行調用功能的提前賦值,方可正常進行測試。
第二個則是啓動了整個Application context,從而調用Controller層的功能進行觸發,其底層功能依賴,比如Service,則無需進行依賴。
第三個功能類似第二種方式,區別在於調用HTTP服務的方式不同,這裏使用TestRestTemplate的實例來進行的。
其他註解
@DataJpaTest
@JsonTest
@WebMvcTest
@RestClientTests
總結
一般情況基於當個層的測試會比較隔離,但是需要自行注入依賴。而基於Spring Boot Test則自動加載了依賴,會比較容易。