Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Spring Autowire stops working when I add the "RunWith" annotation?

Once I add the RunWith annotation, that is @RunWith(PowerMockRunner.class) the Spring Autowire does not work anymore!

class B {  
  @Autowire  
  SessionFactory session;
}

@RunWith(PowerMockRunner.class)  
@PrepareForTest{SomeClass.class}

class Testing {  

  @Test
  methodA(){  
    //mehod 
  }

  @Test
  methodD(){  
  }    
}  

Now, method A makes a call to class B, but due to RunWith(PowerMockRunner) annotation, the Autowiring is not working. Any help would be greatly appreciated!

like image 764
TimeToCodeTheRoad Avatar asked Jul 13 '12 20:07

TimeToCodeTheRoad


2 Answers

In 2016 you can use runner delegate with PowerMockito, effectively using two runners:

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)

More details here: https://github.com/jayway/powermock/wiki/JUnit_Delegating_Runner

like image 134
teejay Avatar answered Sep 29 '22 10:09

teejay


Spring is not magic (even if it seems like it sometimes). No where in your code are you giving spring a chance to start up an application context and do its work of auto wiring your beans. You need to either start the context yourself or switch your test to use @RunWith(SpringJUnit4ClassRunner.class). Unfortunately JUnit only supports a single runner at a time so you'll need to stop using the PowerMockRunner then.

like image 33
jjathman Avatar answered Sep 29 '22 10:09

jjathman