0

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

  }
}
Community
  • 1
  • 1
  • did you try add the `@Autowired` annotation to `myServlet` definition at Unit test like this `@Autowired private MyServlet myServlet;` ? remove `myServlet = new MyServlet();` – David Pérez Cabrera Sep 16 '16 at 07:40
  • @DavidPérezCabrera I followed your instruction and yes it does work!!. But i'd have to add `@Component` to my MyServlet class. I don't think Servlet classes should be annotated with @Component though. – Nissim Pradhan Sep 16 '16 at 08:20
  • Possible duplicate of [Why is my Spring @Autowired field null?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – kryger Sep 16 '16 at 10:06
  • @kryger Yes possibly, But i didn't intend on making my servlet class a bean. So i created this bean through xml only for the test-context. – Nissim Pradhan Sep 19 '16 at 08:39

1 Answers1

0

Add DependencyInjectionTestExecutionListener.class to your TestExecutionListeners. And do not create it with "new MyServlet()" Autowire it

Yuri Plevako
  • 311
  • 1
  • 6