Search code examples
javahttpssljunitwiremock

Method threw 'javax.net.ssl.SSLException' exception


I have written a JUnit to test one of the method which calls below getAuthToken

public String getAuthToken() throws URISyntaxException, IOException, InterruptedException {
    String formBody = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&scope=%s",
            URLEncoder.encode(clientId, StandardCharsets.UTF_8),
            URLEncoder.encode(clientSecret, StandardCharsets.UTF_8),
            URLEncoder.encode(scope, StandardCharsets.UTF_8));

    HttpRequest authRequest = HttpRequest.newBuilder()
            .uri(new URI(epimTokenUri))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .POST(HttpRequest.BodyPublishers.ofString(formBody))
            .build();

    HttpResponse<String> authResponse = client.send(authRequest, HttpResponse.BodyHandlers.ofString());

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(authResponse.body());

    return jsonNode.get("access_token").asText();
}

For this I am using WireMock. Following is mapping for WireMock for getting token

{
  "request": {
    "method": "POST",
    "url": "/.default/token"
  },
  "response": {
    "status": 200,
    "jsonBody": {
      "access_token": "testToken",
      "expires_in": 3600,
      "refresh_expires_in": 0,
      "token_type": "Bearer",
      "not-before-policy": 0,
      "scope": "https://localhost:9082/.default"
    },
    "headers": {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  }
}

This gives error as method threw 'javax.net.ssl.SSLException' exception. at the line HttpResponse<String> authResponse = client.send(authRequest, HttpResponse.BodyHandlers.ofString());

Can anyone please help me on this? What is going wrong here or any other way to mock this method to use in my JUnit? Following is the complete stackTrace enter image description here


Solution

  • In my test.yaml file tokenURI was with https, so it was expecting certs which I was not providing through WireMock. I replaced it with http, and it passed. Another way to solve this is to setup WireMock with certs to accept SSL.