15

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

@RunWith(SpringJUnit4ClassRunner.class) 

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

@Autowired

Someservice someservice ;

But now, I have also integrated PowerMock in it.

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

@RunWith(PowerMockRunner.class)

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

sandy
  • 1,153
  • 7
  • 21
  • 39
Bhuvan
  • 2,209
  • 11
  • 33
  • 46

2 Answers2

16

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

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 !

Pom12
  • 7,622
  • 5
  • 50
  • 69
15

You have to use the 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.

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

Look at the dependecies to 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
alainlompo
  • 4,414
  • 4
  • 32
  • 41
gontard
  • 28,720
  • 11
  • 94
  • 117
  • Hey gontard, I have tried your solution but when I was executing my junit I was getting an exception that PowerMockRule "rule" should be public so I made it public and now I am getting the javassist.NotFoundException. Any thoughts? exeption java.lang.RuntimeException: javassist.NotFoundException: $Proxy88 at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:187) at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:147) .... – Bhuvan Aug 29 '12 at 04:15
  • @bhuvan i don't know, perhaps it is [this issue](http://code.google.com/p/powermock/issues/detail?id=350). I complete my answer too. – gontard Aug 29 '12 at 07:28
  • 4
    @gontard http://powermock.googlecode.com/svn/tags/powermock-1.4.12/examples/spring-mockito/ -- this link is no longer working. – old-monk Oct 10 '17 at 19:01