How to test servlet 3.0 annotations of a base servlet with nested Tomcat 7 in Junit

I want to write a junit test to test tomcat 7's behavior, which is related to servlet 3.0 annotations ( @WebServlet, @ServletSecurity).

What I have so far tested:

@Test
public void testDoGet()
     throws ServletException, LifecycleException, IOException {             
  Tomcat tomcat = new Tomcat();        
  tomcat.setPort(8080);        

  Context ctx = tomcat.addWebapp("/", 
     new File("target").getAbsolutePath());             
  Tomcat.addServlet(ctx, "hello", HelloServlet.class.getName());
  ctx.addServletMapping("/hello", "hello");     
  tomcat.start();

  ByteChunk chunk = new ByteChunk();        
  int responceCode = getUrl("http://127.0.0.1:8080/hello",chunk);

  System.out.println(responceCode + ": " + chunk.toString());

  tomcat.stop();
}

This test works, but it does not account for annotations.

It is clear that this test does not account for annotations in HelloServlet. But I don’t know how to “register” a servlet to use its annotation-based configuration. Can someone give me a hint how to build a test that does this?

+3
source share
2 answers

Servlet 3.0, , @WebServlet @GET, @POST .., ?

, , unit test , , URL- .. , , .

unit test @WebServlet , HTTP-/, , ( ) ( ).

+2

, , 3.0:

ctx.setEffectiveMajorVersion(3);
ctx.setEffectiveMinorVersion(0);
+1

All Articles