public class JsonAPITest {
@Rule
public JenkinsRule j = new JenkinsRule();
private static String GET_API_URL = "custom-api/get-example-param?paramValue=hello";
@Test
public void testGetJSON() throws Exception {
// Testing a simple GET that should answer 200 OK and a JSON
JenkinsRule.JSONWebResponse response = j.getJSON(GET_API_URL);
assertTrue(response.getContentAsString().contains("I am JenkinsRule hello"));
assertEquals(response.getStatusCode(), 200);
}
@Test
public void testAdvancedGetJSON() throws Exception {
//Testing a GET that requires the user to be authenticated
User admin = User.getById("admin", true);
MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
.grant(Jenkins.ADMINISTER).everywhere().to(admin);
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(auth);
//We need to setup the webclient
//By default if the status code is not ok, WebClient throw an exception
//Since we want to assert the error status code, we need to set to false.
JenkinsRule.WebClient webClient = j.createWebClient();
webClient.setThrowExceptionOnFailingStatusCode(false);
// - simple call without authentication should be forbidden
response = j.getJSON(GET_API_URL, webClient);
assertEquals(response.getStatusCode(), 403);
// - same call but authenticated using withBasicApiToken() should be fine
response = j.getJSON(GET_API_URL, webClient.withBasicApiToken(admin));
assertEquals(response.getStatusCode(), 200);
}