简体   繁体   中英

Guice-servlet unit testing

Background: I'm developing servlets using guice with guice-servlet frameworks. I'd like to test my servlets by:

  1. Servlet unit tests : isolating servlets from other dependencies and simulating client, by providing get/post requests
  2. Servlet integration tests : simulating clients, but without servlet isolation. Also, as part of integration tests, I'd like to test my integration with Guice itself.

Question: I'm looking for servlet testing framework which can allow me to perform both kinds of tests described above.

Meanwhile I took a look at HttpUnit , but I didn't find a way to connect Guice to it: servlets can be registered in ServletRunner , but they are provided by class name. This means that ServletRunner will instantiate them (without injecting dependencies).

Also I found tadedon project's GuiceServletMockModule . Seems like exactly what I'm looking for. But I'm not sure it is still maintained. For example, I was not able to fetch their maven package from their maven repository.

Thanks

In order to unit test your servlet (instance of HttpServlet), you do not need any framework - you can just create new instance of the servlet class, and directly call desired method while passing mocked request and response objects.

If you need to isolate your code from Guice dependencies, you can create instance of your class using Injector configured with mocks (in @Before method), for example:

Injector injector = Guice.createInjector( new AbstractModule() {
    @Override
    protected void configure() {
        bind( MyClass.class ).toInstance( mock(MyClass.class) );
        bind( AnotherClass.class ).toInstance( mock(AnotherClass.class) );
    }
} );
//Create new instance of class  that needs injections
ThirdClass thirdInstance = injector.getInstance( ThirdClass.class );

As for the integration tests, you can try to use SoapUI - it works well with SOAP and REST applications, but you can adapt it to generic servlets tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM