即使添加@ PrepareForTest,Mockito仍要求为该类添加@PrepareForTest [英] Mockito asks to add @PrepareForTest for the class even after adding @PrepareForTest

查看:3107
本文介绍了即使添加@ 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆