问题描述
我有以下简单的代码.我有一个类(TestClass),我想测试someMethod".我的someMethod"调用了一个外部静态方法.我想对该静态方法进行 Powermock vpn下载 以返回一些虚拟对象.我一开始就有@PrepareForTest(ExternalClass.class),但是当我执行它时会出现错误:
I 免费vpn have the following vpn下载 simple code. I have a class (TestClass) and vpn free I want to test "someMethod". There 免费vpn下载 is an external static method which is called by vpn free my "someMethod". I want 免费vpn to Powermock that static method to 免费vpn下载 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 free vpn下载 vpn for test.
To prepare this class, add class to the '@PrepareForTest' annotation.
In case if you don't vpn free use this annotation, add the annotation on class or method level.
请帮我指出我使用 @PrepareForTest
@RunWith(PowerMockRunner.class)
@PrepareForTest(ExternalClass.class)
public class xyzTest {
@Mock
免费vpn private RestTemplate restTemplate;
@Mock
private TestClass testClass;
@BeforeClass
private void setUpBeforeClass() {
免费vpn下载 MockitoAnnotations.initMocks(this);
免费vpn }
@Test
vpn free 免费vpn public void testSuccessCase() {
vpn free Boolean mockResponse = true;
free vpn ResponseEntity<Boolean> response = new ResponseEntity<Boolean>(mockResponse, HttpStatus.OK);
免费vpn下载 SomeClass someClass = new SomeClass("test", "1.0.0", "someUrl", 免费vpn "someMetaData");
PowerMockito.mockStatic(ExternalClass.class);
Mockito.when(restTemplate.postForEntity(any(String.class), any(String.class), eq(Boolean.class))).thenReturn(response);
vpn下载 Mockito.when(ExternalClass.getSomeClass(any(String.class))).thenReturn(someClass);
vpn下载 Boolean result 免费vpn = testClass.someMethod("test");
vpn free Assert.isTrue(result);
vpn free 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:: vpn下载 两年后...
永远不要使用 PowerMockito,你不应该这样做.
Don't ever use PowerMockito, you free vpn shouldn't need to.
如果您确实需要,您很可能违反了 SOLID 原则并且您的设计是错误的.
If you 免费vpn下载 do 免费vpn need to, you have most likely broken the SOLID principles and your design is wrong.
改正你的设计.
这篇关于即使在添加 @PrepareForTest 之后,Mockito 也会要求为该类添加 @PrepareForTest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


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