先上service层方法代码
/** * 通过勋章code获取勋章对应的积分 * @param medalCode 勋章code * @return 勋章对应的积分 */ private int getMedalIntegralByMedalCode(String autoshowCode, String medalCode){ String integral = redisClient.hget(CacheConstants.MEDAL_HASHMAP+autoshowCode, medalCode); if(StringUtils.isEmpty(integral)){ List<AsMedal> medalList = asUserIntegralMapper.selectByAutoshowCode(autoshowCode); for(AsMedal medal:medalList){ redisClient.hset(CacheConstants.MEDAL_HASHMAP+autoshowCode,medal.getMedalCode(),String.valueOf(medal.getIntegral())); } integral = redisClient.hget(CacheConstants.MEDAL_HASHMAP+autoshowCode, medalCode); } return integral == null?0:Integer.valueOf(integral); }
测试类需要的依赖先注入到测试类中
@Tested private IntegralServiceImpl targetObject; @Injectable private RedisClient redisClient;
测试方法如下
@Test public void getMedalIntegralByMedalCodeTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { new NonStrictExpectations(){ { redisClient.hget("MEDAL_HASHMAPfrankfurt", "1002"); result = "75"; } }; //通过反射调用私有的方法 Method method = targetObject.getClass().getDeclaredMethod("getMedalIntegralByMedalCode", String.class, String.class); method.setAccessible(true); Integer integral = (Integer) method.invoke(targetObject, "frankfurt", "1002"); Assert.assertEquals(75*1L, integral*1L); }