mock私有方法
被测试的方法是MiddleGroundAppListBO类下的getPromptIdKeyAppPromptInfoMap方法
private Map<Long, AppPromptInfoModel> getPromptIdKeyAppPromptInfoMap(String cubeAppIdentity) {List<AppPromptInfoDO> promptByApp = knowledgeCubeQueryRemoteService.getPromptByApp(cubeAppIdentity);return AppPromptInfoDOConverter.convertToPromptIdKeyMap(promptByApp);}
mock方法编写:
直接middleGroundAppListBO
.getPromptIdKeyAppPromptInfoMap("4HPF1HTFDR") 写就行, groovy和Java不一样,groovy能直接访问private方法.
@Resourceprivate IKnowledgeCubeQueryRemoteService knowledgeCubeQueryRemoteService;def "middleGroundAppListBO.getPromptIdKeyAppPromptInfoMap"() {given:MiddleGroundAppListBO middleGroundAppListBO = new MiddleGroundAppListBO(knowledgeCubeQueryRemoteService: knowledgeCubeQueryRemoteService)when: "测试方法"Map<Long, AppPromptInfoModel> map = middleGroundAppListBO.getPromptIdKeyAppPromptInfoMap("4HPF1HTFDR")log.info("map : {}", map)then: "校验结果"map != null}
PowerMockito
下面的方法我没试过,先记录下,后面有时间我去试试.
测试目标代码:
| 01 | public class ClassUnderTest { |
| 03 | public boolean callPrivateMethod() { |
| 09 | private boolean isExist() { |
测试用例代码:
| 01 | @RunWithclass``) |
| 02 | public class TestClassUnderTest { |
| 05 | @PrepareForTestclass``) |
| 06 | public void testCallPrivateMethod() ``throws Exception { |
| 08 | ClassUnderTest underTest = PowerMockito.mock(ClassUnderTest.); |
| 10 | PowerMockito.when(underTest.callPrivateMethod()).thenCallRealMethod(); |
| 12 | PowerMockito.when(underTest, ).thenReturn(); |
| 14 | Assert.assertTrue(underTest.callPrivateMethod()); |
说明:和Mock普通方法一样,只是需要加注解@PrepareForTest(ClassUnderTest.class),注解里写的类是私有方法所在的类。