开发者

How to test servlet 3.0 annotations base servlet with an embbedded Tomcat 7 in Junit

开发者 https://www.devze.com 2023-02-16 13:14 出处:网络
I want to write a junit test to verify a tomcat 7 behavior, which is related to the Servlet 3.0开发者_StackOverflow社区 annotations (@WebServlet, @ServletSecurity).

I want to write a junit test to verify a tomcat 7 behavior, which is related to the Servlet 3.0开发者_StackOverflow社区 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?


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).


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消