k4sia
k4sia

Reputation: 416

how properly mock UriInfo?

That's my piece of code:

import java.net.URI;
import javax.ws.rs.core.UriInfo;
(...)

    UriInfo mockUriInfo;
    String url = "test";

    mockUriInfo = mock(UriInfo.class);
    when(mockUriInfo.getRequestUri()).then(new URI(url));

Unfortunately I've got an error:

then(org.mockito.stubbing.Answer) cannot be applied to (java.new URI)

Any idea how can i resolve it?

Upvotes: 0

Views: 6587

Answers (2)

bric3
bric3

Reputation: 42223

Don't mock types you don't own

Really it's wrong 99% of the time. Instead it will be better to use real objects or use integration tests (with RESTAssured, or something else).


On the mockito wiki : Don't mock types you don't own !

This is not a hard line, but crossing this line may have repercussions! (it most likely will.)

  1. Imagine code that mocks a third party lib. After a particular upgrade of a third library, the logic might change a bit, but the test suite will execute just fine, because it's mocked. So later on, thinking everything is good to go, the build-wall is green after all, the software is deployed and... Boom
  2. It may be a sign that the current design is not decoupled enough from this third party library.
  3. Also another issue is that the third party lib might be complex and require a lot of mocks to even work properly. That leads to overly specified tests and complex fixtures, which in itself compromises the compact and readable goal. Or to tests which do not cover the code enough, because of the complexity to mock the external system.

Instead, the most common way is to create wrappers around the external lib/system, though one should be aware of the risk of abstraction leakage, where too much low level API, concepts or exceptions, goes beyond the boundary of the wrapper. In order to verify integration with the third party library, write integration tests, and make them as compact and readable as possible as well.

Upvotes: 0

Yosef-at-Panaya
Yosef-at-Panaya

Reputation: 706

you need to use thenReturn and not then:

when(mockUriInfo.getRequestUri()).thenReturn(new URI(url));

if you want to use then (that is a synonym of thenAnswer you need to pass an answer as parameter :

when(mockUriInfo.getRequestUri()).then(new Answer<Integer>() {
    public URI answer(InvocationOnMock invocation) throws Throwable {
        return new URI(url);
    }
}

Upvotes: 2

Related Questions