一、mockito单元测试中常见的几个注解
1. @RunWith(MockitoJUnitRunner.class) 该注解的意思以什么容器来运行单元测试,容器的意思可以理解为运行环境可以解析你的mockito中的注解和语法的意思,这个注解一般加载在你写的单元测试的类上如下

     @RunWith(MockitoJUnitRunner.class)
      public class SendMobileValicodeControllerTest 

2.@InjectMocks 该注解的意思是创建一个实例对象,类似spring中通过 注解注入外部对象一样

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

3.@Mock 这个注解的意思就是模拟,模拟一个对象,用他来构造参数,该注解注释的对象将会被注入到@InjectMocks注解注入的实例中,

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

意思就是 sendMobileValicodeController和switchCache 将会以对象属性的身份注入到sendMobileValicodeController这个对象中,类似spring的注解注入,
4.@Test 注解就是测试的方法,该注解的方法一定要要是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包就可以了在可以这里插入图片描述

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐