I get BeanCreationException
when using @AutoWired
(Spring Annotation) and @PrepareForTest
(PowerMock) and running the TestNG test with the Spring tag.
I have a Spring controller that is scanned through component validation.
I am testing TestNG, Mockito and PowerMock.
I am trying to spy on an auto-wired controller that is connected to the test via: @AutoWired
annotation.
Here is the start of the test class:
@PowerMockIgnore("*")
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
@PrepareForTest(IWantAHamburgerController.class)
public class IWantAHamburgerControllerTest extends AbstractTestNGSpringContextTests {
@Autowired
private WebApplicationContext wac;
@Autowired
private MockHttpSession session;
@Autowired
private MockHttpServletRequest request;
@Autowired
private IWantAHamburgerController iWantAHamburgerController;
private MockMvc mockMvc;
@ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
@BeforeClass
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
I am trying to test the get method on IWantAHamburgerController
. It looks like this:
@Test
public void testGetHamburgerAfterAskingThisQuestion() throws Exception {
Principal p = PowerMockito.mock(Principal.class);
PowerMockito.when(p.getName()).thenReturn("oneofthefiveguys");
IWantAHamburgerController spy = PowerMockito.spy(iWantAHamburgerController);
PowerMockito.doReturn("oneofthefiveguys").when(spy).getUserName("oneofthefiveguys");
mockMvc.perform(get("/hamburgers/everythinghamburger.html")).andExpect(status().isOk())
.andExpect(view().name("jsp/hamburger/everythinghamburger"))
.andExpect(forwardedUrl("jsp/hamburger/everythinghamburger"));
PowerMockito.verifyPrivate(spy).invoke("initGrill", "oneofthefiveguys");
new org.mockito.internal.debugging.MockitoDebuggerImpl().printInvocations(spy);
}
Inside the test, I want to look into autwired IWantAHamburgerController
to verify that the method initGrill
was called by the GET method on the controller.
If I delete @PrepareForTest(IWantAHamburgerController.class)
, I do not receive BeanCreationException
, but then PowerMock does not work.
. IWantAHamburgerController
bean, , ClassCastException
.
:
org.springframework.beans.factory.BeanCreationException: bean 'com.fiveguys.controllers.IWantAHamburgerControllerTest': ; org.springframework.beans.factory.BeanCreationException: autowire: com.fiveguys.controllers.IWantAHamburgerController com.fiveguys.controllers.IWantAHamburgerControllerTest.iWantAHamburgerController; org.springframework.beans.factory.NoSuchBeanDefinitionException: bean [com.fiveguys.controllers.IWantAhamburgerController] :