Reputation: 701
If i need to mock RESTful resource class and the facade method as below, the facade won't be mocked.
e.g.,
@Path("/v1/stocks")
public class StockResource {
@GET
@Path("/{stockid}")
@Produces({ MediaType.APPLICATION_JSON })
public Response getStock(@PathParam("stockid") String stockid) {
Stock stock = TestFacade.findStock(stockid);
if (!ObjectUtils.equals(stock, null)) {
return Response.status(Status.OK).entity(stock).build();
}
return Response.status(Status.BAD_REQUEST).build();
}
}
@RunWith(MockitoJUnitRunner.class)
public class StockTest{
RestClient restClient = new RestClient();
@Mock
private TestFacade facade;
@Test
public void getStockReturnsStock(){
// given
given(facade.findStock(stockid))
.willReturn(new Stock());
Resource resource = restClient.resource(url + "/1234");
// when
ClientResponse response = (ClientResponse) resource.accept(
"application/json").get();
// verify
assertEquals(200, response.getStatusCode());
verify(facade, Mockito.times(1)).findStock("stockid");
}
}
How to mock the facade method call inside RESTful(JAX-RS) resource class? Is there possibility i can mock both resource class and method calls inside it.
Upvotes: 1
Views: 3225
Reputation: 24561
Mockito is not able to stub static method. You need to use PowerMock for that.
But my approach is to rather avoid static methods as much as possible, so that code is testable by plain Mockito.
Here are both approaches in explained in detail: http://lkrnac.net/blog/2014/01/mock-static-method/
Upvotes: 1