代码之家  ›  专栏  ›  技术社区  ›  Jordi

mockito:mock方法抛出异常

  •  1
  • Jordi  · 技术社区  · 6 年前

    我在嘲笑这种方法:

    boolean login() throws SftpModuleException;
    

    模拟代码是:

    Mockito
        .when(this.sftpService.login())
        .thenReturn(true);
    

    既然, login() 抛出一个 SftpModuleException ,编译器告诉我必须处理此异常。

    有没有什么解决办法,因为这个异常永远不会被抛出?

    2 回复  |  直到 6 年前
        1
  •  2
  •   dehasi    6 年前

    我想你可以把这个添加到方法签名中

    @Test
    public void test() throws SftpModuleException {
    
      Mockito
        .when(this.sftpService.login())
        .thenReturn(true);
      // code
    }
    
        2
  •  2
  •   orip    6 年前

    考虑让你的 @Test 方法只声明抛出的异常,甚至声明 throws Exception .

    @Test
    public void testFoo() throws Exception {
      // mocking and test code here
    }