gpt4 book ai didi

java - 模拟抛出异常的服务?

转载 作者:行者123 更新时间:2023-11-30 09:40:29 26 4
gpt4 key购买 nike

我想测试一个委托(delegate)给服务方法“isInProgress”的 JSF Backing-Bean 方法“isInProgress”。当服务方法抛出异常时,bean 应该在特定的事件记录器上放置一个事件并返回 false。

当我调试以下测试时,我进入了捕获 block 。模拟服务不会抛出异常,但会返回一个“默认答案”,该答案对于 boolean 值是假的。 我做错了什么?

我还想知道是否可以以某种方式避免围绕“when”调用的 try-catch,因为实际的异常被被测 bean 吞没了。事实上,我认为“声明式”将方法名称传递给“何时”就足够了。 有没有办法让那个更干净?

@Test
public void testIsInProgressExeption() {
//prepare object and inputs
MyBean bean = new MyBean();
MyService service = mock(MyAdapterService.class);
bean.setService(service);

try {
when(bean.getService().isInProgress()).thenThrow(new Exception());
} catch (Exception e) {

//prepare expected object and result
MyBean expectedBean = new MyBean();
expectedBean.setService(service);
boolean expected = false;

//execute method under test
boolean actual = bean.isInProgress();

//check return values and exceptions
assertEquals(expected, actual);

//check that bean did not change unexpectedly
assertTrue(bean.equals(expectedBean));

//check sideeffects on event log
assertTrue(logEvents.containsMessage("MDI09"));
}

}

此处供引用的是更新后的测试:

@Test
public void testIsInProgressExeption() throws Exception {
//prepare object and inputs
MyBean bean = new MyBean();
MyService service = mock(MyAdapterService.class);
bean.setService(service);

when(bean.getService().isInProgress()).thenThrow(new Exception());

//prepare expected object and result
MyBean expectedBean = new MyBean();
expectedBean.setService(service);
boolean expected = false;

//execute method under test
boolean actual = bean.isInProgress();

//check return values and exceptions
assertEquals(expected, actual);

//check that bean did not change unexpectedly
assertTrue(bean.equals(expectedBean));

//check sideeffects on event log
assertTrue(logEvents.containsMessage("MDI09"));

}

最佳答案

将 when 子句移出 try block 并将其更改为:

when(service.isInProgress()).thenThrow(new Exception());

现在它应该在调用时抛出异常。

关于java - 模拟抛出异常的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9410259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com