java 使用@RunWith Annotation 和 powerMock 时的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12158779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:50:23  来源:igfitidea点击:

issues while using @RunWith Annotation and powerMock

javajunitmockitopowermock

提问by Bhuvan

Initially I was using only Mockito in junits so I was using SpringJUnit4ClassRunner.class in @RunWith annotation ie

最初我只在 junits 中使用 Mockito,所以我在 @RunWith 注释中使用 SpringJUnit4ClassRunner.class,即

@RunWith(SpringJUnit4ClassRunner.class) 

due to which spring dependency injection was working fine and was getting a bean through

由于哪个 spring 依赖注入工作正常并且正在通过一个 bean

@Autowired

Someservice someservice ;

But now, I have also integrated PowerMock in it.

但是现在,我也将 PowerMock 集成到其中。

So as per doc, I have replaced class mentioned in @RunWith annotation with

因此,根据doc,我已将 @RunWith 注释中提到的类替换为

@RunWith(PowerMockRunner.class)

but now, someservice is coming out to be null. Is there a way to use both SpringJUnit4ClassRunner.classand PowerMockRunner.classin @RunWith annotation

但是现在,someservice 出来是空的。有没有办法在@RunWith 注释中同时使用SpringJUnit4ClassRunner.classPowerMockRunner.class

回答by gontard

You have to use the PowerMockRule.

您必须使用PowerMockRule

@RunWith(SpringJUnit4ClassRunner.class) 
@PrepareForTest(X.class)
public class MyTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();

    // Tests goes here
    ...
}

For a full example of the Spring Integration Test with PowerMock and Mockito, you could checkout this maven project.

有关使用 PowerMock 和 Mockito 的 Spring 集成测试的完整示例,您可以查看这个maven 项目

svn co http://powermock.googlecode.com/svn/tags/powermock-1.4.12/examples/spring-mockito/
cd spring-mockito/

Look at the dependecies to powermock.

查看 powermock 的依赖项。

less pom.xml

and then run the test

然后运行测试

mvn test

and you should get the following test results :

你应该得到以下测试结果:

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

回答by Pom12

I know this thread is old, but it's good to add that since 2014 and this pull request, you can use the @PowerMockRunnerDelegateannotation to "delegate" the run context to SpringJUnit4ClassRunner(or any other runner really).

我知道这个线程很旧,但是很高兴添加自 2014 年和这个pull request以来,您可以使用@PowerMockRunnerDelegate注释将运行上下文“委托”给SpringJUnit4ClassRunner(或任何其他运行器)。

Above code would look like :

上面的代码看起来像:

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PrepareForTest(X.class);
public class MyTest {

    // Tests goes here
    ...
}

With this annotation, you don't need the PowerMock rule anymore !

有了这个注解,你就不再需要 PowerMock 规则了!