第一次接触Junit+Mock的单元测试,记一下笔记,慢慢完善。@RunWith(MockitoJUnitRunner.class)@RunWith(PowerMockRunner.class) @PrepareForTest({UserUtil.class}) 这两个注解解决静态方法问题@Mock:注释被测class方法中需要注入的对象 @injectMocks:注释被测class
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 {@InjectMocksprivate ConfigController configController;@Mockprivate ConfigService configService;@Mockprivate HttpServletRequest request;@Mockprivate UserUtil userUtils;@Testpublic 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()));}}