Mockito+PowerMock单元测试
POM文件配置
1 <dependency> 2 <groupId>org.mockito</groupId> 3 <artifactId>mockito-all</artifactId> 4 <version>2.0.2-beta</version> 5 <scope>test</scope> 6 </dependency> 7 8 <dependency> 9 <groupId>org.powermock</groupId> 10 <artifactId>powermock-api-mockito</artifactId> 11 <version>1.7.4</version> 12 <scope>test</scope> 13 </dependency> 14 15 <dependency> 16 <groupId>org.powermock</groupId> 17 <artifactId>powermock-module-junit4</artifactId> 18 <version>1.7.4</version> 19 <scope>test</scope> 20 </dependency>
普通对象方法测试用例
1 @RunWith(SpringJUnit4ClassRunner.class) 2 public abstract class MockitoBasedTest { 3 @Before 4 public void setUp() throws Exception { 5 // 初始化测试用例类中由Mockito的注解标注的所有模拟对象 6 MockitoAnnotations.initMocks(this); 7 } 8 }
1 @RequestMapping("reportSetting") 2 public class ReportSettingController { 3 @Resource 4 private ReportSettingService reportSettingService; 5 6 @PostMapping("addReportSetting") 7 public BaseResponse addReportSetting(@RequestBody @Valid AddReportSettingRequest request) { 8 BaseResponse response = new BaseResponse(); 9 try { 10 String result = reportSettingService.addAllReportSetting(request); 11 if (StringUtils.isBlank(result)) { 12 response.setCode(ConfigConsts.STATUS_CODE_SUCCESS); 13 response.setMessage("设置成功"); 14 } else { 15 response.setCode(ConfigConsts.STATUS_CODE_PARAM_ERROR); 16 response.setMessage("设置失败," + result); 17 } 18 19 return response; 20 } catch (Exception e) { 21 response.setCode(ConfigConsts.STATUS_CODE_INNER_ERROR); 22 response.setMessage("设置异常"); 23 return response; 24 } 25 } 26 }
1 import net.sf.jsqlparser.expression.operators.relational.EqualsTo; 2 import org.junit.Assert; 3 import org.junit.Test; 4 import org.mockito.InjectMocks; 5 import org.mockito.Mock; 6 7 import static org.hamcrest.CoreMatchers.any; 8 import static org.hamcrest.CoreMatchers.equalTo; 9 import static org.junit.Assert.*; 10 import static org.mockito.Matchers.anyObject; 11 import static org.mockito.Mockito.when; 12 13 public class ReportSettingControllerTest extends MockitoBasedTest { 14 15 @InjectMocks 16 private ReportSettingController reportSettingController; 17 @Mock 18 private ReportSettingService reportSettingService; 19 @Test 20 public void addReportSetting() { 21 when(reportSettingService.addAllReportSetting(anyObject())) 22 .thenReturn(null) 23 .thenReturn(" 验证失败") 24 .thenThrow(new RuntimeException("验证异常")); 25 BaseResponse responseSuccess = reportSettingController.addReportSetting(anyObject()); 26 Assert.assertThat(responseSuccess.getCode(), equalTo("200")); 27 BaseResponse responseFailed = reportSettingController.addReportSetting(anyObject()); 28 Assert.assertThat(responseFailed.getCode(), equalTo("400")); 29 BaseResponse responseException = reportSettingController.addReportSetting(anyObject()); 30 Assert.assertThat(responseException.getCode(), equalTo("500")); 31 } 32 }
包含静态方法的测试用例
1 import javax.annotation.Resource; 2 import javax.servlet.http.HttpServletRequest; 3 import javax.servlet.http.HttpServletResponse; 4 import java.io.OutputStream; 5 import java.util.LinkedHashMap; 6 import java.util.List; 7 8 @RequestMapping("sscBenf") 9 public class HrPsLfSscBenfMthController { 10 @Resource 11 private HrPsLfSscBenfMthService hrPsLfSscBenfMthService; 12 13 @Resource 14 private CommonService commonService; 15 16 @Resource 17 private ReportSettingService reportSettingService; 18 19 private static final LinkedHashMap<String, String> MAP_KEY_VALUE = new LinkedHashMap<>(); 20 private static final String CLASS_PATH_Benf = ""; 21 private static final String TITLE_Benf = ""; 22 23 @GetMapping("/exportData") 24 public BaseResponse exportData(HttpServletRequest req, HttpServletResponse resp) { 25 BaseResponse response = new BaseResponse(); 26 String strTitle = ""; 27 try { 28 String authCode = req.getParameter("authCode"); 29 String cLfItemType = req.getParameter("cLfItemType"); 30 String taskBillNumber = req.getParameter("taskbillNumber"); 31 ReportSetting reportSet = reportSettingService.getByTaskbillNumber(taskBillNumber); 32 String yearMonth = reportSet.getReportMonth(); 33 HrPsLfSscBenfMth hrPsLfSscBenfMth = new HrPsLfSscBenfMth(); 34 hrPsLfSscBenfMth.setCLfItemType(cLfItemType); 35 hrPsLfSscBenfMth.setCLfPrdId(yearMonth); 36 strTitle = yearMonth.replaceAll("/", "-") + TITLE_Benf + cLfItemType + "数据"; 37 String fileName = strTitle + ".xls"; 38 resp.setContentType("APPLICATION/OCTET-STREAM"); 39 resp.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); 40 OutputStream out = resp.getOutputStream(); 41 List<HrPsLfSscBenfMth> listOfBenfMthData = hrPsLfSscBenfMthService.selectListOfSscBenfMth(hrPsLfSscBenfMth); 43 ExcelUtil.sayHello() 44 return response; 45 } catch (Exception e) { 46 response.setCode(ConfigConsts.STATUS_CODE_INNER_ERROR); 47 response.setMessage(strTitle + "导出异常"); 48 log.error(strTitle + "数据导出异常:Exception=", e); 49 return response; 50 } 51 } 52 53 }
1 import net.sf.jsqlparser.expression.operators.relational.EqualsTo; 2 import org.junit.Assert; 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.junit.runner.RunWith; 6 import org.mockito.InjectMocks; 7 import org.mockito.Matchers; 8 import org.mockito.Mock; 9 import org.powermock.api.mockito.PowerMockito; 10 import org.powermock.core.classloader.annotations.PrepareForTest; 11 import org.powermock.modules.junit4.PowerMockRunner; 12 import org.springframework.mock.web.MockHttpServletRequest; 13 import org.springframework.mock.web.MockHttpServletResponse; 14 15 import java.util.ArrayList; 16 17 import static org.hamcrest.CoreMatchers.equalTo; 18 import static org.mockito.Matchers.anyObject; 19 import static org.mockito.Matchers.anyString; 20 import static org.powermock.api.mockito.PowerMockito.when; 21 22 @RunWith(PowerMockRunner.class) 23 @PrepareForTest({ExcelUtil.class}) 24 public class HrPsLfSscBenfMthControllerTest { 25 @InjectMocks 26 private HrPsLfSscBenfMthController hrPsLfSscBenfMthController; 27 @Mock 28 private ReportSettingService reportSettingService; 29 @Mock 30 private CommonService commonService; 31 @Mock 32 private HrPsLfSscBenfMthService hrPsLfSscBenfMthService; 33 34 @Before 35 public void init() { 36 PowerMockito.mockStatic(ExcelUtil.class); 37 } 38 39 @Test 40 public void exportData() throws Exception { 41 when(reportSettingService,"getByTaskbillNumber",anyString()).thenReturn(this.getReportSetting()); 42 when(commonService,"authCodeCheck",anyString()).thenReturn(true); 43 when(hrPsLfSscBenfMthService,"selectListOfSscBenfMth", anyObject()).thenReturn(new ArrayList<>());
PowerMockito.when(ExcelUtil.sayHello()).thenReturn("my hello");
44 BaseResponse response_success = hrPsLfSscBenfMthController.exportData(new MockHttpServletRequest(), new MockHttpServletResponse()); 45 Assert.assertThat(response_success.getCode(), equalTo("200")); 46 47 when(commonService,"authCodeCheck",anyString()).thenReturn(false); 48 BaseResponse response_failed = hrPsLfSscBenfMthController.exportData(new MockHttpServletRequest(), new MockHttpServletResponse()); 49 Assert.assertThat(response_failed.getCode(), equalTo("400")); 50 51 when(commonService,"authCodeCheck",anyString()).thenThrow(new RuntimeException("验证异常")); 52 BaseResponse response_excepion = hrPsLfSscBenfMthController.exportData(new MockHttpServletRequest(), new MockHttpServletResponse()); 53 Assert.assertThat(response_excepion.getCode(), equalTo("500")); 54 55 } 56 57 private ReportSetting getReportSetting(){ 58 ReportSetting reportSetting = new ReportSetting(); 59 reportSetting.setReportMonth("2019/10"); 60 return reportSetting; 61 } 62 }