执行单元测试时自动装配在 servlet 中不起作用

Autowire not working in servlet when performing unit test

我有一个标准的 HttpServlet。当我 运行 它在 tomcat 上时,这对 autowire 很好用,我已经使用这个问题的答案完成了这个。

Autowiring in servlet

但是我无法对其进行单元测试。它不会自动连接 bean。我知道这是因为 servlet 没有用 servletConfig 初始化。但是我该怎么做呢?

Servlet Class

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
  }
}

测试Class

@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

  }
}

将 DependencyInjectionTestExecutionListener.class 添加到您的 TestExecutionListeners。 并且不要使用 "new MyServlet()" Autowire it

创建它