Mockito呼び出し静的メソッドとvoidメソッド

3229 ワード

 
  

1 mock 静态方法

mockito库并不能mock静态方法,需要依赖powermock

第一步:给类添加注解

//        ,        powermock       mock
@ContextConfiguration
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PrepareForTest(     .class)

public
class SupplierServiceImplTest extends PowerMockTestCase {}
ステップ2: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());
	//     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));