junit 如何为使用ClientBuilder的AWSLambda/AWSSepFunctions模拟一个新创建的对象?

e4yzc0pl  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(115)

我有一个类,我试着测试它,它创建了一个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),但似乎效果不佳。有没有办法正确返回这个模拟结果?

suzh9iv8

suzh9iv81#

您可以使用Mockito和Junit 5直接模拟静态方法,而无需使用Powermock。

类测试

@Test
    void test() throws IOException {
        try (MockedStatic<AWSStepFunctionsClientBuilder> awsMock = Mockito.mockStatic(AWSStepFunctionsClientBuilder.class, Mockito.RETURNS_DEEP_STUBS)) {
            AWSStepFunctions awsStepFunctionsMock = mock(AWSStepFunctions.class);
            // You can mock methods chaining when you specify Mockito.RETURNS_DEEP_STUBS
            awsMock.when(() -> AWSStepFunctionsClientBuilder.standard().withClientConfiguration(Mockito.any()).build()).thenReturn(awsStepFunctionsMock);

        }
    }

您可以阅读这篇文章,了解更多关于MockedStatic的解释:https://www.baeldung.com/mockito-mock-static-methods
这是关于Mockito的。https://www.baeldung.com/mockito-fluent-apis
不要忘记配置Mockito来处理静态模拟:

测试/资源/mockito扩展/org.mockito.插件.MockMaker

mock-maker-inline

相关问题