jan
jan

Reputation: 4063

GWT RPCServlet - Junit + getThreadLocalRequest

In my RPCServlet I am using the method AbstractRemoteServiceServlet.getThreadLocalRequest() to get the HttpSession. Now I want to unit-test it. I am using Mockito and thought I just could mock everything, but the method is final and protected.

Is there any other way to Unit-test AbstractRemoteServiceServlet.getThreadLocalRequest().getSession()

Upvotes: 0

Views: 334

Answers (1)

apanizo
apanizo

Reputation: 628

At the end you are trying to get a Session. In our case we solve this situation doing this:

Using GUICE for getting our instances (making them available in the GIVEN part of the test)

public class TestServerModule  extends com.google.inject.AbstractModule {
    @Override
    protected void configure() {
      .....
      bind(HttpServletRequest.class).to(MockRequest.class).in(Singleton.class);
      bind(HttpServletResponse.class).to(MockResponse.class).in(Singleton.class);
      ....
    }

    ....

    @Provides
    @Singleton
    RequestUtil getRequestUtil(final HttpServletRequest req, final HttpServletResponse resp) {

      return new RequestUtilsImpl() {
        public HttpServletRequest getThreadRequest() {
          return req;
        }

        public HttpServletResponse getThreadResponse() {
          return resp;
        }
      };
    }

RequestUitl object contains everything related with Session and more server stuff (that is not important for your problem :D). The important part here is you can have access to the getThreadRequest(), so you have access to getSession() method.

What is the problem? You can not have a real HttpServletRequest object in your instances, so you need to mock them. For doing it, we specified the bind rules at the top.

At the end your test should be something like:

@RunWith(...)
@GuiceModules({TestServerModule.class, ....})
public class YourTest extends junit.framework.TestCase {

  @Inject RequestUtil requestUtil;
  ....

  @Test public void
  test_session_after_doing_something() {
     //GIVEN
     HttpSession mockedSession = requestUtil.getThreadRequest().getSession();
     ....
  }


  ....
}

Upvotes: 1

Related Questions