简体   繁体   中英

Mock an exception object (JUnit/Mockito)

I am facing an issue testing a legacy code using JUnit/Mockito, my method throws an exception (HandlerException) which is derived from (BaseException) which is part of our infrastructure.

public class HandlerException extends BaseException

My system-under-test is super simple:

public static void parse(JsonElement record) throws HandlerException
{   
    JsonElement element = record.getAsJsonObject().get(ID_TAG); 
    if(element == null) {
        throw new HandlerException("Failed to find Id ...");
    }
    ...
}

And also the test itself

@Test (expected=HandlerException.class)
public void testParseg() throws HandlerException {
    JsonElement jsonElement = new JsonParser().parse("{}");
    Parser.parse(jsonElement);
}

The problem is with BaseException. It is a complex class and depends on an initialization. Without initializing it BaseException throws an exception in its constructor :( which in turn causes StackOverflowException.

Is it possible to Mock BaseException or HandlerException in any way to avoid this initialization keeping my test simple?

Looks like the answer to my issue was using PowerMockito

First I use @PrepareForTest on my system-under-test (Parser.class)

@RunWith(PowerMockRunner.class)
@PrepareForTest({Parser.class})

Then I mocked the HandlerExeption class using PowerMockito.whenNew

@Mock
HandlerException handlerExceptionMock;

@Before 
public void setup() throws Exception {
    PowerMockito.whenNew(HandlerException.class)
        .withAnyArguments().thenReturn(handlerExceptionMock);
}

@Test (expected=HandlerException.class)
public void testParseg() throws HandlerException {
    JsonElement jsonElement = new JsonParser().parse("{}");
    Parser.parse(jsonElement);
}

This way BaseException was not constructed and my test passed without the need to initialize it.

Note: I am aware that this is not the best practice, however, in my case, I had to since I cannot edit BaseException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM