Mockito asks to add @PrepareForTest for the class even after adding @PrepareForTest(即使在添加 @PrepareForTest 之后,Mockito 也会要求为该类添加 @PrepareForTest)
问题描述
我有以下简单的代码.我有一个类(TestClass),我想测试someMethod".我的someMethod"调用了一个外部静态方法.我想对该静态方法进行 Powermock 以返回一些虚拟对象.我一开始就有@PrepareForTest(ExternalClass.class),但是当我执行它时会出现错误:
I have the following simple code. I have a class (TestClass) and I want to test "someMethod". There is an external static method which is called by my "someMethod". I want to Powermock that static method to return me some dummy object. I have the @PrepareForTest(ExternalClass.class) in the begining, but when I execute it gives the error:
ExternalClass 类没有准备好进行测试.要准备此类,请将类添加到 '@PrepareForTest'
注释.如果您不使用此注解,请在类或方法级别添加注解.
The class ExternalClass not prepared for test.
To prepare this class, add class to the '@PrepareForTest'
annotation.
In case if you don't use this annotation, add the annotation on class or method level.
请帮我指出我使用 @PrepareForTest
@RunWith(PowerMockRunner.class)
@PrepareForTest(ExternalClass.class)
public class xyzTest {
@Mock
private RestTemplate restTemplate;
@Mock
private TestClass testClass;
@BeforeClass
private void setUpBeforeClass() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSuccessCase() {
Boolean mockResponse = true;
ResponseEntity<Boolean> response = new ResponseEntity<Boolean>(mockResponse, HttpStatus.OK);
SomeClass someClass = new SomeClass("test", "1.0.0", "someUrl", "someMetaData");
PowerMockito.mockStatic(ExternalClass.class);
Mockito.when(restTemplate.postForEntity(any(String.class), any(String.class), eq(Boolean.class))).thenReturn(response);
Mockito.when(ExternalClass.getSomeClass(any(String.class))).thenReturn(someClass);
Boolean result = testClass.someMethod("test");
Assert.isTrue(result);
Mockito.verify(restTemplate, times(1)).postForObject(any(String.class), any(String.class), any());
}
}
推荐答案
确保将 @RunWith(PowerMockRunner.class)
也添加到类的顶部.
Make sure you add @RunWith(PowerMockRunner.class)
to the top of your class as well.
::edit:: 两年后...
永远不要使用 PowerMockito,你不应该这样做.
Don't ever use PowerMockito, you shouldn't need to.
如果您确实需要,您很可能违反了 SOLID 原则并且您的设计是错误的.
If you do need to, you have most likely broken the SOLID principles and your design is wrong.
改正你的设计.
这篇关于即使在添加 @PrepareForTest 之后,Mockito 也会要求为该类添加 @PrepareForTest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:即使在添加 @PrepareForTest 之后,Mockito 也会要求为该类添加 @PrepareForTest
基础教程推荐
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01