直接上代码哈,
首先是待测试的service(其中调用了私有方法)
public ResponseResult achieveMedal(String autoshowCode, String medalCode, Integer userId, String tempUserId) { ResponseResult responseResult = new ResponseResult(); responseResult.setReturncode(-1); AsUserIntegral asUserIntegral = new AsUserIntegral(); int integral = getMedalIntegralByMedalCode(autoshowCode, medalCode); if(integral >0){ asUserIntegral.setIntegral(integral); }else { responseResult.setMessage("勋章不存在"); return responseResult; } return responseResult; }
private int getMedalIntegralByMedalCode(String autoshowCode, String medalCode){ return 1; }
下面是jmockit进行单元测试的方法
@Test
public void achieveMedalTest(){
final String autoshowCode = "frankfurt";
final String medalCode = "3003";
final String tempUserId = "14951641585723303";
final Integer userId = 44388195;
new MockUp<IntegralServiceImpl>(){
@Mock
private int getMedalIntegralByMedalCode(String autoshowCode, String medalCode){
return 100;
}
};
new NonStrictExpectations(){//录制预期模拟行为
{
asUserIntegralMapper.selectMedalCountByCond((AsIntegralCond) any);
result = 0;
asUserIntegralMapper.insertSelective((AsUserIntegral) any);
result = 1;
}
};
ResponseResult result = targetObject.achieveMedal(autoshowCode,medalCode, userId, tempUserId);
Assert.assertEquals(result.getResult(), 100);
}
着重看绿色的部分,getMedalIntegralByMedalCode方法是我的私有方法,测试时,期望的返回值是100。这样私有方法就能