vendredi 16 septembre 2016

Autowire not working in servlet when performing unit test

I have a standard HttpServlet. This works fine with autowire when i run it on tomcat, I have accomplised this using the answer on this question .

Autowiring in servlet

But I cannot perform a unit test on it. It doesn't auto wire beans. I understand that it's because the servlet wasn't initialized with a servletConfig. But how can i do this?

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

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

  }
}

Aucun commentaire:

Enregistrer un commentaire