gpt4 book ai didi

java - 静态类模拟中的 org.powermock.api.mockito.ClassNotPreparedException

转载 作者:行者123 更新时间:2023-11-30 01:50:43 27 4
gpt4 key购买 nike

我正在编写一个单元测试来模拟 verticle 中的静态方法,但总是收到 ClassNotPreparedException 。我认为只有类是静态的,但我有非静态类时,才可以以这种方式进行模拟。我错过了什么?

我尝试了各种解决方案,例如使用@rule或@PowerMockIgnore

//myVerticleTest.java

package com.blabla.me.verticles;
import static com.google.common.truth.Truth.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.vertx.core.Vertx;
import io.vertx.junit5.VertxTestContext;
import io.vulpx.VulpxTestBase;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.runner.RunWith;
import com.blabla.me.verticles.AdditionalInformationCardVerticle;
import org.powermock.modules.junit4.rule.PowerMockRule;
import org.junit.Rule;
import com.blabla.me.verticles.st;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ st.class })
@PowerMockIgnore({"org.mockito.*"})
public class myVerticleTest extends VulpxTestBase {
@Rule public PowerMockRule rule = new PowerMockRule();
private Vertx vertx;
private AdditionalInformationCardVerticle dummy;

@BeforeEach
@PrepareForTest({ st.class })
public void setUp(VertxTestContext testContext) throws Exception {
vertx = Vertx.vertx();
try {
PowerMockito.mockStatic(st.class);
PowerMockito.when(st.createClient()).thenReturn("kk");
//deploying verticle
dummy = new AdditionalInformationCardVerticle();
vertx.deployVerticle(dummy, testContext.completing());
} catch (Exception e) {
System.out.println("heyyy eroorrr : " + e);
}
}
@Test
@PrepareForTest({ st.class })
public void justnormaltest() {
cla ownclass = new cla();
String k = ownclass.createfromclass();
assertThat("kk").isEqualTo(k);
}
}
// st.java 
public class st {
public static String createClient() {
return "kk";
}
}
// cla.java
public class cla {
public String createfromclass() {
return st.createClient();
}
}

我希望它运行断言,但我总是得到低于期望的结果:“org.powermock.api.mockito.ClassNotPreparedException:com.sap.me.verticles.st 类未准备测试。要准备此类,请将类添加到“@PrepareForTest”注释中。如果您不使用此注释,请在类或方法级别添加注释。 ”

最佳答案

这里:

@PrepareForTest({ st.class })

那个去恰好一个地方:在你的测试类public class myVerticleTest前面。

提示:不要向不工作的代码中添加越来越多的“东西”:选择任何好的文档,并尝试遵循到最后;在示例代码中(而不是假设在这里或那里添加越来越多的东西会有帮助)。

一个好的起点:官方documentation关于静态模拟。

当然,通常的警告:首先考虑不要学习 PowerMock。相反,专注于编写“易于测试”的代码。人们常常认为 PowerMock(ito) 是他们问题的答案。当他们的现实问题是无法编写“易于测试”的生产代码时。

关于java - 静态类模拟中的 org.powermock.api.mockito.ClassNotPreparedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149645/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com