3
votes

I want to write a junit test to verify a tomcat 7 behavior, which is related to the Servlet 3.0 annotations (@WebServlet, @ServletSecurity).

What I have so far is this test:

@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 pay any respect to the annotation.

It is clear that this test does not pay any respect to the annotations at HelloServlet. But I have no clue how to “register” a servlet so that its annotation based configuration is used. Can anyone give me a hint how to build a test that do that?

2
there is a bug in tomcat-7.0.8->7.0.11 where @servletSecurity is ignored. Maybe your test is correct and you don't have anything to do, you are just triggering the bug and you test is failing as it should. mail-archive.com/[email protected]/msg87337.htmlJean
@Jean: I know the bug, but I am using 7.0.11.Ralph

2 Answers

2
votes

I am not totally familiar with the Servlet 3.0 annotations, but my understanding is that you tag a class with @WebServlet and annotate a method with one of @GET, @POST, etc., correct?

If so then I do not think that a unit test of the servlet class should involve anything related to Contexts, URL paths, etc. If your tests is testing this logic, then you are testing the code and logic of the application server rather than your own class.

In a unit test of a @WebServlet I would stick to testing the methods that handle the HTTP request/response and assert that given certain input (in the request) your servlet returns the expected output (in the response).

1
votes

I don't know if that solves the problem, but you can explicitly set the servlet version to 3.0:

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