【发布时间】:2021-05-24 08:41:20
【问题描述】:
@Override
public void contextDestroyed(ServletContextEvent sce) {
try{
DateUtil.clean();
}catch(Exception e){
LOGGER.error("MyServletContextListener contextDestroyed error: ", e);
}
我正在对上面的代码进行单元测试,并试图通过点击 Exception 子句来获得 100% 的行覆盖率,但是,我似乎无法让它与我的实现一起工作。将不胜感激任何帮助。请在下面查看我的实现。
@Test (expected= Exception.class)
public void test_contextDestroyed_Exception() {
DateUtil wrapper = Mockito.spy(new DateUtil());
Exception e = mock(Exception.class);
when(wrapper).thenThrow(e);
Mockito.doThrow(e)
.when(myServletContextListener)
.contextDestroyed(sce);
myServletContextListener.contextDestroyed(sce);
}
【问题讨论】:
-
首先你正在尝试模拟静态方法。尝试使用电源模拟。你应该写
when(DateUtil.clean ()).thenThrow(e) -
嗨@ShirishkumarBari,我试过你提到的,但我得到一个''when (T) in Mockito cannot be applied to (void) reason: no instances(s) of type variable(s) ) T 存在,因此 void 符合 T。" 错误
-
尝试使用 PowerMockito