简体   繁体   English

如何验证是否捕获到异常

[英]How to verify if an exception is caught

How to test if an exception is caught with Mockito? 如何测试Mockito是否有异常?

Example: 例:

try{
     int a = 8/0;
catch(ArithmeticException e){
    Logger.error(e.getMessage());
}

I guess your problem is that Logger.error() is actually a call to a static method. 我想你的问题是Logger.error()实际上是对静态方法的调用。 And "normal" Mokito doesn't allow you to mock calls to static methods. 而“普通”Mokito不允许您模拟对静态方法的调用。

Thus, there are two choices: 因此,有两种选择:

a) you could turn to PowerMokito ... which enables you to mock such calls; a)你可以转向PowerMokito ...它可以让你模拟这样的电话; and thereby you can simply specify: "I expect that Logger.error() should be called with this kind of exception object". 因此,您可以简单地指定:“我希望使用这种异常对象调用Logger.error()”。 But be warned: PowerMockito and its brother PowerMock come at certain cost; 但要注意:PowerMockito及其兄弟PowerMock需要付出一定代价; for many people they create more problems than they solve. 对于许多人来说,他们创造的问题比他们解决的问 So, personally, I absolutely do not recommend this option. 所以,就个人而言,我绝对不推荐这个选项。

b) you could step back, and change your design to not use static methods, like: b)您可以退后一步,并将您的设计更改为不使用静态方法,例如:

class UnderTest {
   SomeLogger logger ... coming into the class via dependency injection

   void foo() {
      try { ... whatever  
      } catch(WhateverException w) {
        logger.error(w....

So, now you are dealing with a method call; 所以,现在你正在处理一个方法调用; and you can create a mock and pass that. 你可以创建一个模拟并传递它。

But of course, that only works if you own the logging code for example. 但是,当然,只有拥有日志记录代码才有效。 And of course, it might be a lot of work. 当然,这可能需要做很多工作。 But in the long run, it will pay off. 但从长远来看,它会得到回报。

Final advise: you might want to watch those videos , explaining in great detail what "writing testable code" is actually about. 最后建议:你可能想要观看那些视频 ,详细解释“编写可测试代码”的实际内容。

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

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