[英]Using Mockito how to ensure that an exception was thrown in a method
I am using Mockit.我正在使用 Mockit。 I have a situation in which a method throws an exception, catches the exception and logs the exception (and without re-throwing).
我有一个方法抛出异常,捕获异常并记录异常(并且不重新抛出)的情况。
Class Test {
public void abc() {
try {
xyz();
} catch (Exception e) {
LOGGER.error("Exception thrown {} ", e);
}
}
private void xyz() {
// Can throw exception
// which goes to the
// callee
}
}
Now, for some scenarios xyz() can throw exception and which is caught in abc().现在,对于某些情况 xyz() 可以抛出异常并在 abc() 中捕获。 It is this scenario I want to test.
这是我想测试的场景。 I can't use
@Test(Expected=SomeException.class)
as the exception is being caught and logged.我不能使用
@Test(Expected=SomeException.class)
因为正在捕获和记录异常。 However, my test case should look if this exception thrown.但是,我的测试用例应该查看是否抛出此异常。
I did search online, however didn't find anything relevant.我确实在网上搜索过,但没有找到任何相关内容。
Any pointer in how to approach would be helpful.任何有关如何接近的指示都会有所帮助。
I referred to this SO question , which seems similar , but isn't what I am looking for.我提到了这个 SO question ,它看起来很相似,但不是我要找的。
IMO, Basically you have two options: IMO,基本上你有两个选择:
Mock the logger (do whatever you need for this - refactoring, powermock, etc) this was already described in comments.模拟记录器(做任何你需要的事情 - 重构、powermock 等)这已经在评论中描述了。 Other than stating (based on my personal experience ) that usually usage of PowerMock is discouraged I can't really add much to it.
除了声明(根据我的个人经验)通常不鼓励使用 PowerMock 之外,我不能真正添加太多内容。
Use a "creative" workaround: Add an artificial appender to the logger associated with the class programmatically from within the test.使用“创造性”的解决方法:在测试中以编程方式向与类关联的记录器添加人工附加器。 The appender is a "special" one that would store the logging event and will provide an access to it for verification:
appender 是一个“特殊”的,它将存储日志事件并提供对它的访问以进行验证:
// pseudo code that might vary depending on the actual logging framework of your choice
class MyTestAppender extends Appender {
private LoggingEvent evt = null;
public void doAppend(LoggingEvent evt) {
this.evt = evt;
}
public LoggingEvent getEvent() {
return this.evt;
}
}
// in test:
@Test
void test() {
Logger logger = LoggerFactory.getLogger(ClassUnderTest.class);
MyTestAppender myTestAppender = new MyTestAppender();
logger.addAppender(myTestAppender);
classUnderTest.doStuff();
// now you can verify whether the event has been logged (and stored by the appender):
LoggingEvent evt = myTestAppender.getEvent();
assertNotNull(evt); // cool, something was really logged, lets see what:
assertThat( // verify message, cause exception, whatever you want here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.