簡體   English   中英

執行單元測試時,Autowire在Servlet中不起作用

[英]Autowire not working in servlet when performing unit test

我有一個標准的HttpServlet。 當我在tomcat上運行autowire時,它可以很好地工作,我已經使用此問題的答案來完成此工作。

在servlet中自動裝配

但是我無法對其進行單元測試。 它不會自動切絲豆。 我知道這是因為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

  }
}

將DependencyInjectionTestExecutionListener.class添加到您的TestExecutionListeners中。 並且不要使用“ new MyServlet()”創建它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM