我有一个类,我试着测试它,它创建了一个AWSSepFunctions类型的新对象,我试着模拟它,返回一个相同类型的模拟。我不能改变这行原始代码,我只能添加测试,所以我想知道我该如何模拟它。
这个班级看起来是这样的
Class class{
public Object handleRequest(Object object, Context context) {
AWSStepFunctions client = AWSStepFunctionsClientBuilder.standard().withClientConfiguration(new ClientConfiguration()).build();
client.startExecution(...);
}
}
测试代码如下所示-
public class ClassTest {
@Test
public void testHandlerRequest() {
mockStatic(AWSStepFunctionsClientBuilder.class); //mockStatic() and when() from PowerMockito
AWSStepFunctions awsStepFunctionsMock = mock(AWSStepFunctions.class);
AWSStepFunctionsClientBuilder awsStepFunctionsClientBuilder = mock(AWSStepFunctionsClientBuilder.class);
ClientConfiguration configuration = mock(ClientConfiguration.class);
PowerMockito.whenNew(ClientConfiguration.class).withAnyArguments().thenReturn(awsStepFunctionsMock);
when(awsStepFunctionsClientBuilder.standard()).thenReturn(awsStepFunctionsClientBuilder);
when(awsStepFunctionsClientBuilder.withClientConfiguration()).thenReturn(awsStepFunctionsClientBuilder);
when(awsStepFunctionsClientBuilder.build()).thenReturn(awsStepFunctionsMock);
... more when-thenreturns
}
}
我遇到了一些错误,例如clientBuilder的模拟出现了NoSuchMethodError。
我尝试使用PowerMockito的whenNew来模拟创建AWSSepFunctions类型的新对象- PowerMockito.whenNew(AWSSepFunctions.class).withAnyArguments().thenReturn(awsStepFunctionsMock),但似乎效果不佳。有没有办法正确返回这个模拟结果?
1条答案
按热度按时间suzh9iv81#
您可以使用Mockito和Junit 5直接模拟静态方法,而无需使用Powermock。
类测试
您可以阅读这篇文章,了解更多关于MockedStatic的解释:https://www.baeldung.com/mockito-mock-static-methods
这是关于Mockito的。https://www.baeldung.com/mockito-fluent-apis
不要忘记配置Mockito来处理静态模拟:
测试/资源/mockito扩展/org.mockito.插件.MockMaker