我遇到了一个使用JUnit/Mockito测试遗留代码的问题,我的方法抛出了一个异常(HandlerException),这个异常是从(BaseException)派生的,它是我们基础架构的一部分。
public class HandlerException extends BaseException我的被测系统非常简单:
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 ...");
}
...
}还有测试本身
@Test (expected=HandlerException.class)
public void testParseg() throws HandlerException {
JsonElement jsonElement = new JsonParser().parse("{}");
Parser.parse(jsonElement);
}问题出在BaseException上。它是一个复杂的类,依赖于初始化。在没有初始化的情况下,BaseException会在其构造函数中抛出一个异常:(这反过来会导致StackOverflowException。
有没有可能以任何方式模拟BaseException或HandlerException来避免这种初始化,从而使我的测试变得简单?
发布于 2018-04-23 04:07:36
看起来我的问题的答案是使用PowerMockito
首先,我在被测系统(Parser.class)上使用@PrepareForTest.
@RunWith(PowerMockRunner.class)
@PrepareForTest({Parser.class})然后我使用PowerMockito.whenNew模拟了HandlerExeption类
@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);
}这样,BaseException就不会被构造出来,我的测试也就通过了,不需要初始化它。
注意:我知道这不是最佳实践,但是,在我的例子中,我不得不这样做,因为我不能编辑BaseException。
https://stackoverflow.com/questions/49964459
复制相似问题