使用JUnit时,是否可以验证在测试方法中是否调用了try/catch指令的Catch部分? [英] Is there a way to verify if the Catch part of a try/catch instruction is called in a test method when using JUnit?

查看:327
本文介绍了使用JUnit时,是否可以验证在测试方法中是否调用了try/catch指令的Catch部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有以下要测试的课程:

For example, if I had the following class that I want to test:

public class SomeClass{
    public void someMethod() {
        try {
            //Some code, where comething could go wrong
        } catch (Exception err) {
            //Handling it amounts to logging the problem and trying to continue
        }
    }
 }

如果我随后用JUnit测试此方法,则在try子句中确实出现问题并且运行catch代码,则测试将通过.

If I then test this method with JUnit, then if something does go wrong in the try clause and the catch code is run, then the test will pass.

我想这样做,以便如果执行catch子句指令,则测试将失败.

I want to make it so that the test will fail if the catch clause instructions are run.

我确实想到了几种尝试编写测试的方法,以便获得同等的功能,但是有每种我不希望以这种方式实现的原因.如果实际上可能的话,试图通过测试是否达到任何catch子句是最干净的方法

I did think of a few ways I could try and write tests so that I get an equivalent sort of functionality, but there are reasons for each one that I do not want to approach it that way. It seems like trying to fail the test if any catch clause is reached is the cleanest way to do this, if that is in fact possible

注释:

我知道我可以验证代码的某些功能,并检查它们是否具有特定值/是否已在Mockito中运行了很多次.但是,我需要一个解决方案,如果对测试方法进行了更改,从根本上改变了它的工作方式(但本质上不是在执行什么任务),那么我就不必重写测试.

I know I could verify certain features of the code and check if they are a certain value/have been run a number of times with Mockito. However I want a solution where if changes were made to the test method that radically altered how it worked (but not what task was essentially being carried out) then I won't have to rewrite the test.

不幸的是,仅仅为了使这个问题更加困难,我无法对源代码进行任何修改.这个职位是我无法控制的,所以我必须在这些范围内工作.

Unfortunately, just to make this proble more difficult, I am unable to make any modifictions to the source code. This position is out of my control so I have to work within these confines.

SomeClass是我要测试的类.这不是实际的JUnit测试.我已经编辑了原始问题,以试图澄清这一点.

SomeClass is the class that I wish to test. It is not the actual JUnit test. I have edited my original question to try and clarify this.

推荐答案

我以前不得不处理这种问题.我最终模拟了日志子系统(不简单,但又不太复杂),并听取了有趣的"日志调用,然后在发生故障时进行标记.

I've had to deal with this sort of problem before. I ended up mocking the logging sub-system (not simple but not overly complex) and listened for the 'interesting' logging calls, and then flagging failures when it happened.

这篇关于使用JUnit时,是否可以验证在测试方法中是否调用了try/catch指令的Catch部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆