1. 程式人生 > >如何用mockito來寫單元測試

如何用mockito來寫單元測試

一、mockito單元測試中常見的幾個註解
1. @RunWith(MockitoJUnitRunner.class) 該註解的意思以什麼容器來執行單元測試,容器的意思可以理解為執行環境可以解析你的mockito中的註解和語法的意思,這個註解一般載入在你寫的單元測試的類上如下

     @RunWith(MockitoJUnitRunner.class)
      public class SendMobileValicodeControllerTest 

[email protected] 該註解的意思是建立一個例項物件,類似spring中通過 註解注入外部物件一樣

   @RunWith(MockitoJUnitRunner.class)
   public class SendMobileValicodeControllerTest {
   @InjectMocks
   SendMobileValicodeController sendMobileValicodeController;

[email protected] 這個註解的意思就是模擬,模擬一個物件,用他來構造引數,該註解註釋的物件將會被注入到@InjectMocks註解注入的例項中,

    @RunWith(MockitoJUnitRunner.class)
    public class SendMobileValicodeControllerTest {
   @InjectMocks
   SendMobileValicodeController sendMobileValicodeController;
	@Mock
   private SendMobileMsgService sendMobileMsgService;
	@Mock
    private SwitchCache switchCache;

意思就是 sendMobileValicodeController和switchCache 將會以物件屬性的身份注入到sendMobileValicodeController這個物件中,類似spring的註解注入,
[email protected] 註解就是測試的方法,該註解的方法一定要要是public方法,程式碼如下

   public void testSendMobileValicode() throws Exception {
	String data="{\r\n" + 
			" \"mobileNo\":\"18710841160\",\r\n" + 
			" \"openId\":\"1qaz2sxx3edc\",\r\n" + 
			" \"batchId\":\"plmijb789456\",\r\n" + 
			" \"userIp\":\"127.0.0.1\"\r\n" + 
			"}";	
	ResultObject resultObject=new ResultObject(SmsReturnCodeEnum.SUCCESS.getCode(), SmsReturnCodeEnum.SUCCESS.getErrMsg());
	String expectStr=JSONObject.toJSONString(resultObject);
	
	SMSReturnMsgHead smsReturnMsgHead=new SMSReturnMsgHead();
	smsReturnMsgHead.setRespCode("1");
	smsReturnMsgHead.setRespMsg("簡訊傳送成功");
	
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContent(data.getBytes());
	MockHttpServletResponse response = new MockHttpServletResponse();

	when(switchCache.getSMSTYPE()).thenReturn(SwitchCache.SMSTYPE_SQLSERVER);
	when(sendMobileMsgService.sendMobileValicodeNew("18710841160","1qaz2sxx3edc","plmijb789456","127.0.0.1")).thenReturn(Boolean.TRUE);
	String retStr=sendMobileValicodeController.sendMobileValicode(request, response);	       
	System.out.println("str>>"+retStr);
	Assert.assertTrue(retStr.equals(expectStr));
	
	when(switchCache.getSMSTYPE()).thenReturn(SwitchCache.SMSTYPE_INTERFACE);
	when(sendMobileMsgService.sendMobileValicode("18710841160","1qaz2sxx3edc","plmijb789456","127.0.0.1")).thenReturn(smsReturnMsgHead);
	retStr=sendMobileValicodeController.sendMobileValicode(request, response);	       
	System.out.println("str>>"+retStr);
	Assert.assertTrue(retStr.equals(expectStr));
	
	resultObject=new ResultObject(SmsReturnCodeEnum.FAILED.getCode(),null);
	expectStr=JSONObject.toJSONString(resultObject);
		
	when(sendMobileMsgService.sendMobileValicode("18710841160","1qaz2sxx3edc","plmijb789456","127.0.0.1")).thenReturn(null);
	retStr=sendMobileValicodeController.sendMobileValicode(request, response);	       
	System.out.println("str>>"+retStr);
	Assert.assertTrue(retStr.equals(expectStr));
}

5.引入mockito註解需要的jar包就可以了在可以這裡插入圖片描述