Lesson 18 of 21
Throw Errors with Powermock
A quick demo showing how to make static methods throw errors with Powermock.
In this lesson
Roy Osherove shows how to make the write method of a static logger throw an exception with PowerMock (external link, opens in new tab): after mock static, doThrow with an out of memory exception is set on the static logger class, and the next call to the static logger is the one that throws. He notes that this API is not obvious at first and that a matcher such as any string tells the reader more.
Transcript
[00:03] (external link, opens in new tab) I didn't show how to throw how to throw expect exceptions with the PowerMock (external link, opens in new tab). So this is a very simple demo for that. Now it looks weird the first time you do it but if I wanted the write method of static logger to throw an exception I would have to do this. I do the mock static just like before. I say do throw new out of memory exception when then I say static logger.class class not the method that's the limitations of the API and then the next call to the static logger is the thing that will throw the exception
[00:42] (external link, opens in new tab) Okay so it's better to use a matcher like any string etc so that the reader will know a bit more that this is a thing or maybe it's better to do something like this maybe that's a bit more readable I'm not sure Maybe this way. Either way, I wanted to show that this thing is somehow connected to the things above. Okay? So, it's not very obvious when you just start to use the API.
[01:14] (external link, opens in new tab) So, you should know how to do that. How to simulate behavior from something static. Okay?