1

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.

user3587174
  • 661
  • 3
  • 8
  • 13
  • I had a EJB lookup issue other than that seems it works. And no need to write client code for request and response. I can mock the methods in the resource class now. – user3587174 Oct 02 '14 at 23:59

1 Answers1

1

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/

luboskrnac
  • 23,973
  • 10
  • 81
  • 92