前一段時間,有朋友問到springboot運用如何進行單元測試,結合LZ公司的實際運用,這里給大家描述一下三種單元測試的方式。
1.約定
單元測試代碼寫在src/test/java目錄下
單元測試類命名為*Test,前綴為要測試的類名
2. 使用mock方式單元測試
Spring測試框架提供MockMvc對象,可以在不需要客戶端-服務端請求的情況下進行MVC測試,完全在服務端這邊就可以執行Controller的請求,跟啟動了測試服務器一樣。
測試開始之前需要建立測試環境,setup方法被@Before修飾。通過MockMvcBuilders工具,使用WebApplicationContext對象作為參數,創建一個MockMvc對象。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)//這里的Application是springboot的啟動類名
@WebAppConfiguration
public class StyleControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private ObjectMapper mapper = new ObjectMapper();
@Before
public void setupMockMvc() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testSend() throws Exception {
Long id =1l;
//調用接口,傳入添加的用戶參數
mockMvc.perform(MockMvcRequestBuilders.get("/style/listStyleById")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(mapper.writeValueAsString(id)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultHandlers.print());
}
}
3. 使用Feign方式單元測試
以下是Feign接口的單元測試示例,啟動項目,可以測試本jar提供的服務,不啟動服務,改為遠程服務地址,可以測試遠程jar提供的服務
其中
@EnableFeignClients(clients = UserControllerTest.UserServiceFeignClient.class)
類似我們實際應用調用相關服務一樣。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = UserControllerTest.class)
@Import({ FeignAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class })
@EnableFeignClients(clients = UserControllerTest.UserServiceFeignClient.class)
public class UserControllerTest {
@FeignClient(value = "loan-server", url = "http://localhost:9070/")
public interface UserServiceFeignClient extends UserServiceClient {
}
@Autowired
private UserServiceFeignClient userServiceFeignClient;
@Test
public void getUser() {
User user = userServiceFeignClient.getSDKUserById(1);
System.out.println(user);
}
}
4. 使用Http Rest API 單元測試
使用RestTemplate發起GET或POST請求,其中@SpringBootTest這兩行注釋掉就不啟動SpringBoot容器直接進行遠程調用測試
@RunWith(SpringJUnit4ClassRunner.class)
public class LoanControllerTest {
private final static String url = "http://localhost:9070/";
private static RestTemplate restTemplate = new RestTemplate();
@Test
public void test(){
ResponseEntity<String> response = restTemplate.exchange(url + "/loan/getLoanById?id=1" ,
HttpMethod.GET,
new HttpEntity(null),
String.class);
System.out.println("result: " + response.getBody());
}
}
歡迎大家掃碼關注我的微信公眾號,與大家一起分享技術與成長中的故事。