0

我有一堂课

class A {

    @Autowired
    DbObject dbObject;

    method1 () {
        try {
            return DbObject.read("query").getItem ();
        }
        catch (NotFoundException e) {
            return null;
        }
    }

}

如果抛出 NotFound Exception,我必须测试 method1 是否返回 null,我将在测试类中为 DbObject 创建@MockBean。如何编写一个 when 条件来模拟 getItem()。when(DbObject.method1("query")).thenThrow("NotFoundException") 。但这不会模拟在我们的模拟 when(DbObject.method1("query")) 返回的对象上调用的 getItem 方法。

4

1 回答 1

0

为此,您需要使用模拟方法的链接。声明两个模拟:一个用于dbObject,另一个用于返回结果dbObject.read("query")(我们称之为dbObjectQueryResult)。

when(dbObject.read("query")).thenReturn(dbObjectQueryResult);
when(dbObjectQueryResult.getItem()).thenThrow(new NotFoundException("test")) 
于 2020-07-05T18:09:00.950 回答