jeudi 6 février 2020

Mockito: Why is `HttpClientErrorException` not caught after `thenThrow`?

I'm writing a unit test which tests that when an exception is thrown, it is caught and the code inside catch is executed.

public void putDataSomewhere(Doc doc) {
    for (int i = 0; i < S3Constants.S3_DOCUMENT_UPLOAD_ATTEMPTS; i++) {
        try {
            restTemplate.postForEntity(thing.getUri(), doc.toJSONString(), String.class);
            break;
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            //other stuff to test
        }
    }
}

But when I write this test and run with coverage:

 @Test
    public void testExceptionCaughtWhenThrownByRestTemplate(){
        doc = new Doc():
        doc.setStuff("stuff");
        when(restTemplate.postForEntity(any(URI.class), any(String.class), any(Class.class))).thenThrow(HttpClientErrorException.class);
        myService.putDataSomewhere(doc);
    }

my catch is never executed, I've run a test, just in case, to check break; isn't executed after the exception is thrown and it isn't.

Why is HttpClientErrorException not caught after thenThrow?

Aucun commentaire:

Enregistrer un commentaire