lundi 26 octobre 2020

How do you mock a simple Webservice with Mockito?

I have been trying to solve this for a while now but just can't figure out how it works. I have a simple java method that makes a PUT on a webservice and gives back whether it was successfull or not. If it was successfull, it will return true, otherwise false.

public static boolean Putt(URL url) {
        boolean output = false;

        try {
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("PUT");
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.connect();
            int responsecode = con.getResponseCode();

            if ((responsecode < 200) || (responsecode > 299)) {
                output = false;
            } else {
                output = true;
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        return output;
    }

Now, I am supposed to test this method and write 2 JUnit tests, one for a successfull put, and one for a failed one. Our Professor recommended using Mockito, but I just can't figure out how to properly mock it. Can you give me any hints on how you would do something like this?

Aucun commentaire:

Enregistrer un commentaire