Junit+Mock 迈不过友情╰ 2022-11-28 10:41 157阅读 0赞 第一次接触Junit+Mock的单元测试,记一下笔记,慢慢完善。 1.@RunWith(MockitoJUnitRunner.class) 2.@RunWith(PowerMockRunner.class) @PrepareForTest({UserUtil.class}) 这两个注解解决静态方法问题 3.@Mock:注释被测class方法中需要注入的对象 @injectMocks:注释被测class 4.Mockito.verify(testService, times(1)).testFunction(arg); 校验调用某个方法的次数;times(0)校验没有调用某个方法 5.when(...) thenReturn(...)会调用真实的方法 例:when(configConbinationInstanceMapper.selectInstanceList(any(Long.class),any(String.class),any(String.class))).thenReturn(list); Assert.assertNotNull();//断言某个值 不为空,如果为空就抛出异常 Assert.assertThat("200", is(pageInfoBaseResponse.getCode()));//如果pageInfoBaseResponse.getCode()为"200"则测试通过 Assert.assertEquals("200", pageInfoBaseResponse.getCode());//如果pageInfoBaseResponse.getCode()为"200"则测试通过 例子: @RunWith(PowerMockRunner.class) @PrepareForTest({EasyExcel.class, UserUtil.class}) public class TestT { @InjectMocks private ConfigController configController; @Mock private ConfigService configService; @Mock private HttpServletRequest request; @Mock private UserUtil userUtils; @Test public void delete() { PowerMockito.mockStatic(UserUtil.class); ConfigReqVo reqVo = new ConfigReqVo(); CasUser user = new CasUser(); user.setUsername("lks"); when(userUtils.getUser()).thenReturn(user); when(configService.deleteById(any(ConfigReqVo.class))).thenReturn(Boolean.TRUE); BaseResponse<Boolean> delete = configController.delete(reqVo, request); Assert.assertNotNull(delete); Assert.assertEquals("200", delete.getCode()); Assert.assertThat(Boolean.TRUE, is(delete.getData())); Mockito.verify(configService, times(1)).deleteById(reqVo ); } }
还没有评论,来说两句吧...