Affects: \6.1.11
This commit to improve the message for WebClientResponseException has broken some of our unit tests with setup that look like this:
doThrow(WebClientResponseException.BadGateway::class)
.whenever(someService).someMethod(anyString())
The exception thrown by Mockito is "hollow" in that it has no status code or any other details:
So the test fails with Cannot invoke "org.springframework.http.HttpStatusCode.is1xxInformational()" because "this.statusCode" is null
.
I guess the question is - is it fair to assume that WebClientResponseException has a status code? If so this code is fine and I'll need to ask Mockito to fix or find a workaround. If there are genuine reasons for having a null status code then you might need to add some null checks?
Comment From: Tree4Free
You can also pass an instance of an exception to the doThrow method, so something like:
Exception e = new WebClientResponseException.BadGateway();
e.setStatusCode(...);
doThrow(e).whenever ...;
(I did not check if the BadGateway
exception has such a setter but I hope you get the idea)
Comment From: snicoll
is it fair to assume that WebClientResponseException has a status code?
Yes.
If so this code is fine and I'll need to ask Mockito to fix or find a workaround.
Your code isn't IMO. There's really no reason to mock the exception in the case above. @Tree4Free provided an example.
Comment From: NicoStrecker
I would also have prefered a if check before the statuscode so the tests would still work
Comment From: mikehalmamoj
@NicoStrecker If you look at how WebClientResponseException is constructed (with a factory method including the status) then I think it's a fair assumption that every one has a status code.
I think the real problem is that on doThrow(Class clazz)
Mockito uses reflection to create an instance of the Class - this means you're not testing the real method of constructing the class, so the test is almost meaningless. Therefore the workaround suggested above is the best way to use doThrow
and if anything Mockito should only accept real exceptions and avoid reflection in this case.