1 mock 静态方法
mockito库并不能mock静态方法,需要依赖powermock
第一步:给类添加注解
@ContextConfiguration
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PrepareForTest(静态调用类.class)
public
class SupplierServiceImplTest extends PowerMockTestCase {}
第二步:mock使用
@Test(expectedExceptions = BusinessException.class)
public void testAddSupplierAccount_genIdentityNoError() {
PowerMockito.mockStatic(PasswordGenerator.class);
final SupplierAccountDto supplierAccountDto = new SupplierAccountDto();
supplierAccountDto.setName("小明");
final String randomPWd = "666";
PowerMockito.when(supplierDao.selectByEmail(anyString()))
.thenReturn(new ArrayList<HaitaoSupplier>());
PowerMockito.when(PasswordGenerator.genPwd()).thenReturn(randomPWd);
PowerMockito.when(pwEncoder.encode(anyString())).thenReturn(randomPWd);
PowerMockito.when(identityNoGenerator.genIdentityNo()).thenReturn(-1L);
supplierServiceImpl.addSupplierAccount(supplierAccountDto);
verify(pwEncoder).encode(randomPWd);
}
2 mock void 方法
PowerMockito.doNothing().when(casService).addSupplier(anyLong(), any(ServiceKey.class));