Skip to content

Mocking Unirest with mockito

I am in my starting programming phase and I wanted to ask about mocking Objects with Mockito, more specifically is the Unirest response. Let’s say I have a database, and I dont what to bother it every time I do testing, and I want to use Mockito for that, but the problem is I am not sure how to create the fake “httpResponse” object that will come back. To give some context, I have attached my code:

 * This method lists the ID of the activity when requested.
 * @return the list of all activities
public  JSONArray getActivites() {
    HttpResponse<JsonNode> jsonResponse = null;
    try {
        jsonResponse = Unirest
                .header("accept", "application/json")
    } catch (UnirestException e) {
        System.out.println("Server is unreachable");

    JSONArray listOfActivities = jsonResponse.getBody().getArray();
    return listOfActivities;

So what I had in mind, is to mock Unirest, and then when a .get method gets invoked, I would return a fake HttpResponse, problem is, I am not sure how to, I have looked online and couldn’t really make much sense of it. Is it possible to do it 1 time with the actual Database, and then “Extract” the information and to use that every time for testing?


Sample Snippet with PowerMockRunner, PowerMockito and Mockito

    @PrepareForTest({ Unirest.class})
    public class TestApp{

      public void setup() {

      public void shouldTestgetActivites() throws UnirestException {