问题描述
我有以下简单的代码.我有一个类(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)