Mocking protected function with mockito

1.6k Views Asked by At

I am trying to write a unit test for a GWT Servlet. Therefore i need to mock the getThreadLocalRequest() function of AbstractRemoteServiceServlet so that i dont get NPE's.

The function is protected so according to the mocktio faq it should be possible to mock it as long as I am inside the same package. So I tried the following:

HttpServletRequest request = mock(HttpServletRequest.class);
svc = spy(new GreetingServiceImpl());
doReturn(request).when(svc).getThreadLocalRequest();

But I get the following error that the function isnt visible:

The method `getThreadLocalRequest()` from the type `AbstractRemoteServiceServlet` is not visible

I would appreciate any advices on the problem or hints on a better solution of my problem.

1

There are 1 best solutions below

2
On

Mockito can't modify the java rules for visibility and the return value of when(svc) isn't in a package where getThreadLocalRequest() is visible.

Make sure that your test class is in the same package as AbstractRemoteServiceServlet or call the getThreadLocalRequest method is via reflection:

Method getThreadLocalRequestMethod = AbstractRemoteServiceServlet.class.getDeclaredMethod("getThreadLocalRequest");
Object target = doReturn(request).when(svc);
Object regetThreadLocalRequestMethod.invoke(target);