Spring TestNG PowerMock测试

时间:2015-10-24 22:53:11

标签: spring spring-mvc testng powermock spring-test

使用BeanCreationException(Spring Annotation)和@AutoWired(PowerMock)并运行启用Spring的TestNG测试时,我得到@PrepareForTest

我有一个Spring控制器,通过组件扫描拾取。

我正在测试TestNG,Mockito和PowerMock。

我正试图通过:@AutoWired注释监视自动连接到测试中的自动有线控制器。

这是测试类的开始:

@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();

         // see the note at the bottom of this post about this line
         //iWantAHamburgerController = (IWantAHamburgerController) applicationContext.getBean("iWantAHamburgerController");
     }

我正在尝试在IWantAHamburgerController上测试GET方法。这就是测试的样子:

    @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);
    }

在测试中,我想监视自动装配的iWantAHamburgerController,以验证控制器上的GET方法是否调用了initGrill

如果我删除@PrepareForTest(IWantAHamburgerController.class)我没有BeanCreationException,但PowerMock无效。

注意:我尝试手动设置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]   依赖:预期

0 个答案:

没有答案