简体   繁体   English

Mockito:模拟方法引发异常

[英]Mockito: mock method throws exception

I'm trying to mock this method: 我正在尝试模拟此方法:

boolean login() throws SftpModuleException;

Mocking code is: 模拟代码为:

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

Since, login() throws an SftpModuleException , compiler tells me that this exception has to be handled. 由于login()抛出SftpModuleException ,因此编译器告诉我必须处理此异常。

Is there any work around due to this exception will never be thrown? 是否有任何变通办法,因为不会抛出此异常?

I think you can add this to a method signature 我认为您可以将此添加到方法签名中

@Test
public void test() throws SftpModuleException {

  Mockito
    .when(this.sftpService.login())
    .thenReturn(true);
  // code
}

Consider having your @Test method simply declare the exceptions being thrown, or even declaring throws Exception . 考虑让@Test方法简单地声明要抛出的异常,甚至声明throws Exception

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM