Reputation: 792
I have researched a lot, but not able to find proper solution,
I have a method in service class which is calling a consumer like below
try {
snsProducer.send(message);
} catch (JsonProcessingException jpe) {
throw new SnSException(
"Could not parse Message to publish to SNS");
}
I am trying to cover catch block through test cases but still not successful.
Here is what I have tried
@Test
void snsTest() {
when(service.doCreate(message)).thenThrow(new JsonProcessingException("Json Processing Error"){});
assertThrows(SnSException.class,()-> service.doCreate(message));
}
but this throws Checked exception is invalid for this method!
I tried this too
when(service.doCreate(message)).thenThrow(new JsonProcessingException("Exception"){});
assertThrows(SnStateException.class,()-> service.doCreate(message));
but this throws this error
Expected SnSException to be thrown, but nothing was thrown.
Complete Test case
@Test
void doCreateTest(){
String id = RandomStringUtils.randomAlphanumeric(20);
Subscription subscription = testUtils.createEntity(sId,RandomStringUtils.randomAlphanumeric(20));
Manifest manifest = new Manifest();
manifest.setCommon(new Common());
doReturn(manifest).when(manifestUtils).getManifestWithLatestVersion(any());
when(service.doCreate(subscription)).thenThrow(new JsonProcessingException("Exception"){});
assertThrows(SnSException.class,()-> service.doCreate(subscription));
}
I am not sure what I am doing wrong, Any help would be appriciated
Upvotes: 0
Views: 147
Reputation: 2270
From your code, I can see that snsProducer.send(message) is throwing checked exception JsonProcessingException. So when().thenThrow() should be written around it.
@Test
void snsTest() {
when(snsProducer.send(message)).thenThrow(new JsonProcessingException("Json Processing Error"){});
assertThrows(SnSException.class,()-> service.doCreate(message));
}
Upvotes: 1