【问题标题】:How to mock the method invoked on the reponse of a mocked method如何模拟在模拟方法的响应上调用的方法
【发布时间】:2020-07-05 14:51:33
【问题描述】:

我有课

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

【问题讨论】:

    标签: spring-boot junit mockito springmockito


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多