org.powermock.api.mockito.ClassNotPreparedException 声明为准备就绪时

问题描述 投票:0回答:2

我不明白为什么会出现这种情况,因为我的测试明确要求 PowerMock 做好准备。

@PrepareForTest({AmazonSQSClientBuilder.class})
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.*", "org.apache.logging.*"})
class EncodingAdapterTest {

    ...
    private AmazonSQSClientBuilder sqsBuilder;
    private AmazonSQS sqsClient;
    private AmazonSNS snsClient;
    private SendMessageResult sqsResult;
    private PublishResult snsResult;

    @BeforeEach
    void setUp() {
       
        sqsClient = PowerMockito.mock(AmazonSQS.class);
        PowerMockito.mockStatic(AmazonSQSClientBuilder.class);
        AmazonSQSClientBuilder mockBuilder = PowerMockito.mock(AmazonSQSClientBuilder.class);
        PowerMockito.when(AmazonSQSClientBuilder.standard()).thenReturn(mockBuilder);
        sqsBuilder = PowerMockito.mock(AmazonSQSClientBuilder.class);
    }

虽然我一开始就有

@PrepareForTest({AmazonSQSClientBuilder.class})
,但它显示第
PowerMockito.mockStatic(AmazonSQSClientBuilder.class);
行的错误。

错误如下:

[Ljava.lang.Object;@259661b4
The class com.amazonaws.services.sqs.AmazonSQSClientBuilder not prepared for test.
org.powermock.api.mockito.ClassNotPreparedException: 

[Ljava.lang.Object;@259661b4
The class com.amazonaws.services.sqs.AmazonSQSClientBuilder not prepared for test.
    at org.powermock.api.mockito.expectation.reporter.MockitoPowerMockReporter.classNotPrepared(MockitoPowerMockReporter.java:29)
    at org.powermock.api.mockito.internal.mockcreation.MockTypeValidatorFactory$DefaultMockTypeValidator.validate(MockTypeValidatorFactory.java:37)
    at org.powermock.api.mockito.internal.mockcreation.AbstractMockCreator.validateType(AbstractMockCreator.java:10)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:49)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:40)
    at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:62)
    at package.adapters.EncodingAdapterTest.setUp(EncodingAdapterTest.java:76)

我错过了什么吗?

java junit mockito powermock powermockito
2个回答
0
投票

您可以尝试延长

PowerMockTestCase
。它会解决你的问题。

class EncodingAdapterTest extends PowerMockTestCase 

顺便说一句,我建议使用mockito-inline而不是Powermock来模拟静态方法或类。因为它比Powermock更容易、更流行。您可以轻松模拟静态,无需多余的注释,如下所示:

try (MockedStatic<AmazonSQSClientBuilder> builder = Mockito.mockStatic(AmazonSQSClientBuilder.class)) {
        builder.when(() -> AmazonSQSClientBuilder.standard())
        .thenReturn("somthing");
}

参考:https://www.baeldung.com/mockito-mock-static-methods


0
投票

您正在

mockStactic
中使用
BeforeEach
,请尝试将其放入
Before

© www.soinside.com 2019 - 2024. All rights reserved.