Unit test - Junit4+EasyMock build unit test

Posted by curby on Mon, 09 Dec 2019 11:27:50 +0100

Add dependency

pom.xml

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.easymock</groupId>
	<artifactId>easymock</artifactId>
	<version>3.1</version>
	<scope>test</scope>
</dependency>

Note that the dependency scope is set to test, and the project package will ignore the test dependency.

Test implementation class

BizRefApi.java ``` @Slf4j @RestController @RequestMapping("bizRefApi/") public class BizRefApi { /** *Business processing interface < br > */ @Resource private BizRefService bizRefService;

	/**
	 * Business cache processing interface < br >
	 */
	@Resource
	private BizRefCacheService bizRefCacheService;
	/**
	 * Description: New business association < br >
	 * 
	 * @author xubin<br>
	 * @taskId <br>
	 * @param addBizRefReq New request parameters
	 * @param request HttpServletRequest
	 * @return <br>
	 */
	@PostMapping(value = "/addBizRef")
	public String addBizRef(@RequestBody AddBizRefReq addBizRefReq, HttpServletRequest request) {
		try {
			ValidateUtil.validate(addBizRefReq);
		} catch (Exception e) {
			log.error("addBizRef fail, param : {}, exception : {}", addBizRefReq.toString(), e.getMessage());
			return JsonUtil.getErrorJson(WebConstant.PARAM_EXCEPTION);
		}
		BizRefBO bizRefBO = new BizRefBO();
		BeanUtils.copyProperties(addBizRefReq, bizRefBO);
		bizRefBO.setAppKey(request.getHeader(CommonConstant.APP_KEY));
		bizRefService.save(bizRefBO);
		return JsonUtil.getSucc(WebConstant.OPER_SUCC);
	}
	/**
	 * Description: Query the associated object ID of the business module corresponding to a single device < br >
	 * 
	 * @author xubin<br>
	 * @taskId <br>
	 * @param queryBizIdReq Request parameter object
	 * @param request HttpServletRequest
	 * @return <br>
	 */
	@PostMapping(value = "/v2/queryBizIdSet")
	public String queryBizIdSet(@RequestBody QueryBizIdByDeviceCodeReq queryBizIdReq, HttpServletRequest request) {
		try {
			ValidateUtil.validate(queryBizIdReq);
		} catch (Exception e) {
			log.error("queryBizIdSet fail, param : {}, exception : {}", queryBizIdReq.toString(), e.getMessage());
			return JsonUtil.getErrorJson(WebConstant.PARAM_EXCEPTION);
		}
		Set<String> resList = bizRefCacheService.queryBizIdByDeviceCode(request.getHeader(CommonConstant.APP_KEY), queryBizIdReq.getDeviceCode(),
				queryBizIdReq.getModuleCode());
		return JsonUtil.getSucc4data(resList);
	} 
	/**
	 * set bizRefService
	 * 
	 * @param bizRefService The bizRefService to set. <br>
	 */
	public void setBizRefService(BizRefService bizRefService) {
		this.bizRefService = bizRefService;
	}

	/**
	 * set bizRefCacheService
	 * 
	 * @param bizRefCacheService The bizRefCacheService to set. <br>
	 */
	public void setBizRefCacheService(BizRefCacheService bizRefCacheService) {
		this.bizRefCacheService = bizRefCacheService;
	}
```

The specific mechanism of the implementation class will not be described in detail. This article mainly talks about unit testing with EasyMock. It should be noted that setter methods should be set for the injected objects (bizRefService, bizRefCacheService) in the implementation class for later unit testing.

Unit test Case

	public class TestBizRefApi {

		/**
		 * Description: Test add business association < br >
		 * 
		 * @author xubin<br>
		 * @taskId <br>
		 *         <br>
		 */
		@Test
		public void testAddBizRef() {
			// 1. Normal execution
			//Simulate vo request parameters
			BizRefService bizRefServiceMock = EasyMock.createMock(BizRefService.class);
			HttpServletRequest requestMock = EasyMock.createMock(HttpServletRequest.class);
			bizRefApi.setBizRefService(bizRefServiceMock);
			// The method being mocked has no return value (void). If there is a return value, the expected value of EasyMock.expect needs to be set
			bizRefServiceMock.save(EasyMock.anyObject());
			// Set the expected value of the mock object calling method
			EasyMock.expect(requestMock.getHeader(CommonConstant.APP_KEY)).andReturn("");
			// Activate the mock object
			EasyMock.replay(bizRefServiceMock);
			EasyMock.replay(requestMock);
			// Execution target test method
			String resJsonStr = bizRefApi.addBizRef(addBizRefReq, requestMock);
			// Verify execution results
			TestCase.assertEquals(WebConstant.OPER_SUCC, JSONObject.parseObject(resJsonStr).getJSONArray("resMsg").getJSONObject(0).getString("msgCode"));
			// Verify the execution status of the mock object
			EasyMock.verify(bizRefServiceMock, requestMock);
			// 2. Parameter exception
			addBizRefReq = new AddBizRefReq();
			// To reset the mock object, call when the parameters of the mock object need to be reset
			// EasyMock.reset(bizRefServiceMock);
			// EasyMock.reset(requestMock);
			resJsonStr = bizRefApi.addBizRef(addBizRefReq, requestMock);
			TestCase.assertEquals(WebConstant.PARAM_EXCEPTION,
					JSONObject.parseObject(resJsonStr).getJSONArray("resMsg").getJSONObject(0).getString("msgCode"));
			EasyMock.verify(bizRefServiceMock, requestMock);
		}

		/**
		 * Description: The test queries the business id set according to the equipment code < br >
		 * 
		 * @author xubin<br>
		 * @taskId <br>
		 *         <br>
		 */
		@Test
		public void testQueryBizIdSet() {
			// 1. Normal execution
			QueryBizIdByDeviceCodeReq queryBizIdReq = new QueryBizIdByDeviceCodeReq();
			queryBizIdReq.setDeviceCode("222");
			queryBizIdReq.setModuleCode("faceset");
			BizRefApi bizRefApi = new BizRefApi();
			BizRefCacheService bizRefCacheServiceMock = EasyMock.createMock(BizRefCacheService.class);
			HttpServletRequest requestMock = EasyMock.createMock(HttpServletRequest.class);
			bizRefApi.setBizRefCacheService(bizRefCacheServiceMock);
			EasyMock.expect(requestMock.getHeader(CommonConstant.APP_KEY)).andReturn("");
			Set<String> resSet = Sets.newHashSet();
			resSet.add("1");
			EasyMock.expect(bizRefCacheServiceMock.queryBizIdByDeviceCode(EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject()))
					.andReturn(resSet);
			EasyMock.replay(bizRefCacheServiceMock);
			EasyMock.replay(requestMock);
			String resJsonStr = bizRefApi.queryBizIdSet(queryBizIdReq, requestMock);
			TestCase.assertEquals(1, JSONObject.parseObject(resJsonStr).getJSONArray("resData").size());
			EasyMock.verify(bizRefCacheServiceMock, requestMock);
			// 2. Parameter exception
			queryBizIdReq = new QueryBizIdByDeviceCodeReq();
			resJsonStr = bizRefApi.queryBizIdSet(queryBizIdReq, requestMock);
			TestCase.assertEquals(WebConstant.PARAM_EXCEPTION,
					JSONObject.parseObject(resJsonStr).getJSONArray("resMsg").getJSONObject(0).getString("msgCode"));
			EasyMock.verify(bizRefCacheServiceMock, requestMock);
		}

Commonly used EasyMock methods: EasyMock.createMock: new mock object EasyMock.expect(m).andReturn(v): set the expected return value of M method execution to v EasyMock.expect(m).andThrow(Throwable throwable): set the m method execution to throw an exception EasyMock.replay: activate the mock object EasyMock.verify: verify whether the mock object executes EasyMock.reset: reset the mock object

Unit test coverage

I use eclipse Plug-in EclEmma to view unit test coverage

  • Run unit tests with plug-ins:

  • You can see the coverage in the test class. Green means covered, red means not covered:

Topics: Programming Junit Spring xml Java