java - How do I instantiate an unirest HttpResponse<JsonNode> for my mock? -
let's have class called api , has method:
public class api{ public httpresponse<jsonnode> request() { try { return unirest.get("http://localhost:8080").header("accept", "application/json").asjson(); } catch (unirestexception e) { throw new runtimeexception(e); } } }
and have class:
public class dao(){ private api api; public dao(api api){ this.api = api; } public integer test(){ integer result = api.request().getinteger("result"); return result + 100; } }
in test want test business logic based on response api.request method returns.
something like:
import static org.mockito.mockito.mock; import static org.mockito.mockito.stub; import org.json.jsonobject; import com.mashape.unirest.http.httpresponse; public class apitest { private api api = mock(api.class); public void test() { httpresponse<jsonnode> response = null; jsonobject result = new jsonobject(); response.getbody().getobject(); stub(api.request("")).toreturn(response); dao dao = new dao(api); asserttrue(dao.test() > 100); } }
how instantiate httpresponse body "{ number: 10 }" able return mock?
this how it:
public class dao() { private api api; public dao(api api){ this.api = api; } public integer test(){ // not style // should iterate through pulling out each piece integer result = api.request().getbody().getobject().getinteger("result"); return result + 100; } } public class apitest { private api api = mock(api.class); public void test() { jsonnode json = new jsonnode("{\"result\":10}"); httpresponse<jsonnode> mockresponse = mock(httpresponse.class); when(mockresponse.getcode()).thenreturn(200); when(mockresponse.getbody()).thenreturn(json); when(api.request(anystring())).thenreturn(mockresponse); dao dao = new dao(api); // should done more well, check code/body/etc.. asserttrue(dao.test() > 100); } }
Comments
Post a Comment