简体   繁体   English

Mockito,带有检查异常的 void 方法

[英]Mockito, void method with checked exception

I want to know why i need to handle exception ,when i am mocking a void method which throws exception.我想知道为什么我需要处理异常,当我模拟一个抛出异常的 void 方法时。

For example例如

public class MyObject {
    public void call() throws SomeException {
        //do something
        }
}

Now when i am doing this,现在当我这样做时,

@Mock
MyObject myObject;

doNothing().when(myObject).call()

it results in compilation error saying它导致编译错误说

"error: unreported exception SomeException; must be caught or declared to be thrown" “错误:未报告的异常 SomeException;必须被捕获或声明为抛出”

I am wondering , why i need to handle exception for the method, which is itself being mocked .我想知道,为什么我需要处理该方法的异常,该方法本身正在被嘲笑。

When you mock an object using Mockito in Java.当您在 Java 中使用 Mockito 模拟对象时。 The framework doesn't change anything to the language specification.该框架不会对语言规范进行任何更改。 And in Java, the throws clause is defined at the compilation.而在 Java 中, throws子句是在编译时定义的。 You can't change the declared exceptions at runtime.您不能在运行时更改声明的异常。 In your case, if you call the method MyObject.call() , you have to handle the SomeException as in any normal Java code.在您的情况下,如果您调用方法MyObject.call() ,则SomeException像在任何普通 Java 代码中一样处理SomeException

Since in unit test, you don't want to handle with things you are not testing.因为在单元测试中,你不想处理你没有测试的事情。 In your case, I would simply redeclare throws SomeException in the test method.在你的情况下,我会简单地在测试方法中重新声明throws SomeException

I was having a similar issue with multiple checked exceptions.我遇到了多个检查异常的类似问题。 My code looked something like this:我的代码看起来像这样:

public class MyObject {
    public void call() throws ExceptionOne, ExceptionTwo {
        //do something
        }
}

and my test was:我的测试是:

@Mock
MyObject myObject;

@Test
public void exampleTest throws ExceptionOne {
    doThrow(new ExceptionOne()).when(myObject).call()
    // assert...
}

the error message was unreported exception: ExceptionOne错误消息是unreported exception: ExceptionOne

The solution was to have exampleTest throw both exceptionOne AND exceptionTwo.解决方案是让exampleTest抛出exceptionOne 和exceptionTwo。 if you only report one checked exception it's not going to run.如果您只报告一个已检查的异常,它就不会运行。

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

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