执行单元测试时,Autowire无法在servlet中工作

时间:2016-09-16 07:35:12

标签: java spring unit-testing servlets config

我有一个标准的HttpServlet。当我在tomcat上运行它时,这与autowire工作正常,我已经用这个问题的答案完成了这个。

Autowiring in servlet

但是我不能对它进行单元测试。它没有自动连线bean。我理解这是因为servlet没有用servletConfig初始化。但我怎么能这样做?

Servlet类

public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

  public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
      config.getServletContext());
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) {
      myService.doSomething();// myService is null on unit test
  }
}

测试类

@ContextConfiguration(locations = {"classpath:META-INF/spring/test-context.xml"})
@Transactional
@TransactionConfiguration(defaultRollback = true)
@TestExecutionListeners({TransactionalTestExecutionListener.class})
public class MyServletTest extends AbstractTransactionalTestNGSpringContextTests{

  private MockHttpServletRequest request;
  private MockHttpServletResponse response;
  private MyServlet myServlet;

  @Test(enabled=true)
  public void test() throws Exception {
    myServlet = new MyServlet();
    myServlet.init();
    //myServlet.init(servletConfig); //Where can i get this
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();

    //Add stuff to request
    .
    .
    .
    myServlet.doPost(request,response); 
    //request goes through but myService throws a null pointer exception

  }
}

1 个答案:

答案 0 :(得分:0)

将DependencyInjectionTestExecutionListener.class添加到TestExecutionListeners。 并且不要使用" new MyServlet()"自动装载