我有类似的声明
public void dummyMethod() {
CreateTableRequest ctr = dynamoDBMapper.generateCreateTableRequest(RolePolicies.class);
ctr.setProvisionedThroughput(new ProvisionedThroughput(30L, 5L));
TableUtils.createTableIfNotExists(amazonDynamoDB, ctr);
}
我正在尝试使用以下方法为其创建UT:
@PrepareForTest(TableUtils.class)
@Test
public void verifyRoleTableOnDynamo() throws Exception
{
Mockito.doReturn(new CreateTableRequest()).when(dynamoDBMapper).generateCreateTableRequest(any());
Mockito.doReturn(new CreateTableResult()).when(amazonDynamoDB).createTable(ctr);
PowerMockito.mockStatic(TableUtils.class);
Mockito.when(tableUtils_mock.createTableIfNotExists(mock(AmazonDynamoDB.class),mock(CreateTableRequest.class)))
.thenReturn(true); //This line throws Exception
// PowerMockito.doReturn(true).when(TableUtils.createTableIfNotExists(amazonDynamoDB,ctr));
testClassObject.dummyMethod();
//There should be no Exception in this case.
Assert.assertTrue(true); // Other Assert
}
PowerMockito代替了模拟并返回值,而是调用了createTableIfNotExists方法的实际实现:
我收到错误消息:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:布尔值 无法由createTable()返回createTable()应该返回 CreateTableResult
仅供参考: Amazon SDK将其实现为:
public static final boolean createTableIfNotExists(final AmazonDynamoDB dynamo, final CreateTableRequest createTableRequest) {
try {
dynamo.createTable(createTableRequest);
return true;
} catch (final ResourceInUseException e) {
//Statements
}
return false;
}
答案 0 :(得分:0)
@PrepareForTest
是在类级别而不是方法
@RunWith(PowerMockRunner.class)
@PrepareForTest(TableUtils.class) //<-- Add @PrepareForTest at class level.
public class MyTest {
@Test
public void verifyRoleTableOnDynamo() throws Exception {
//Arrange
PowerMockito.mockStatic(TableUtils.class); //<-- Call PowerMockito.mockStatic() to mock a static class
//Just use Mockito.when() to setup your expectation:
Mockito.when(TableUtils.createTableIfNotExists(any(AmazonDynamoDB.class), any(CreateTableRequest.class)))
.thenReturn(true).;
//Act
testClassObject.dummyMethod();
//There should be no Exception in this case.
Assert.assertTrue(true); // Other Assert
}
}