如何模拟在模拟方法的响应上调用的方法

时间:2020-07-05 14:51:33

标签: spring-boot junit mockito springmockito

我上课

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方法。

1 个答案:

答案 0 :(得分:0)

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

when(dbObject.read("query")).thenReturn(dbObjectQueryResult);
when(dbObjectQueryResult.getItem()).thenThrow(new NotFoundException("test"))