Mockito呼叫靜態方法和void方法
阿新 • • 發佈:2019-02-13
1 mock 靜態方法
mockito庫並不能mock靜態方法,需要依賴powermock
第一步:給類添加註解
// 靜態類優先載入,所以需要提前告訴powermock哪些靜態類需要mock
@ContextConfiguration @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) @PrepareForTest(靜態呼叫類.class)public class SupplierServiceImplTest extends PowerMockTestCase {}
第二步:mock使用
@Test(expectedExceptions = BusinessException.class)
public void testAddSupplierAccount_genIdentityNoError() {
// 告訴powermock,需要mock該類的所有靜態方法
PowerMockito.mockStatic(PasswordGenerator.class);
final SupplierAccountDto supplierAccountDto = new SupplierAccountDto();
supplierAccountDto.setName("小明" );
final String randomPWd = "666";
PowerMockito.when(supplierDao.selectByEmail(anyString()))
.thenReturn(new ArrayList<HaitaoSupplier>());
// 靜態方法mock
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 方法
// void嘛,doNothing顧名思義
PowerMockito.doNothing().when(casService).addSupplier(anyLong(), any(ServiceKey.class));