繁体   English   中英

是否可以将Intellij-IDEA配置为中断JUnit测试中的异常,以使测试失败?

[英]Can Intellij-IDEA be configured to break on exceptions in JUnit tests that lets the test fail?

当我有一个JUnit测试时,我希望调试器能够在测试代码中抛出任何异常的位置停止,以便测试失败,以便检查错误。 是否有可能配置IntelliJ的调试器来做到这一点,而不是打破其他异常?

如果我在任何未捕获的异常上设置了异常断点,那么这不起作用,因为JUnit捕获了异常。 如果我尝试使用catch类org.junit对捕获的异常进行断点中断,那也不起作用,因为异常在Javas反射机制到达JUnit之前被Javas反射机制捕获并包装。 所以我在这里有点不知所措 - Eclipse只是停在原来的例外。

澄清:我在讨论代码I测试中的异常或从那里调用的代码,而不是测试中的断言失败。 例如,考虑以下测试:

@Test
public void thisShouldBreak() {
    int i = 25 - 25;
    int j = 17 / i;
}


private void neverBreakHereSinceThisIsCaught() {
    int i = 14 - 14;
    int j = 29 / i;
}

@Test
public void thisShouldNotBreak() {
    try {
        neverBreakHereSinceThisIsCaught();
    } catch (ArithmeticException e) {
        // ignored or handled
    }
}

@Test
public void thisShouldNotBreakEither() {
    try {
        getClass().getDeclaredMethod("neverBreakHereSinceThisIsCaught").invoke(this);
    } catch (Exception e) {
        // ignored or handled
    }
}

我希望IntelliJ在抛出ArithmeticException的地方执行测试thisShouldBreak时停止,这样我就可以检查导致异常的i的值。 但是,我不希望IntelliJ在neverBreakHereSinceThisIsCaught停止,因为抛出的异常没有到达JUnit。 我尝试失败: - 在neverBreakHereSinceThisIsCaught, too, and loads of other places. - an exception breakpoint only on uncaught exception is never hit at all, since JUnit catches and wraps those exceptions. - a catch class filter捕获的异常中断的异常断点neverBreakHereSinceThisIsCaught, too, and loads of other places. - an exception breakpoint only on uncaught exception is never hit at all, since JUnit catches and wraps those exceptions. - a catch class filter neverBreakHereSinceThisIsCaught, too, and loads of other places. - an exception breakpoint only on uncaught exception is never hit at all, since JUnit catches and wraps those exceptions. - a catch class filter neverBreakHereSinceThisIsCaught, too, and loads of other places. - an exception breakpoint only on uncaught exception is never hit at all, since JUnit catches and wraps those exceptions. - a catch class filter org.junit。*`也打破了JUnit的JUnit端Java反射调用的许多内部位置。

您可以添加一个过滤器来检查堆栈跟踪是否包含您的包。 它可能会使执行速度变慢,但它不会因JUnit初始化异常而停止,这些异常不会阻止测试执行,只有在调用涉及某些类时它才会停止。 有点像:

条件

这就是我做的:

你基本上想要做的是告诉Intellij停止任何异常(Caught&Uncaught),其中catch类过滤器是junit,因此只有junit捕获异常会导致调试器停止。

这是我的Intellij设置: Intellij断点设置

当您使用像Tomcat这样捕获异常的应用服务器时,您可能会遇到类似的问题。 同样,您将通过Tomcat包过滤catch类。

我如何处理这个问题:

  1. 将Java Exception Breakpoint设置为java.lang.AssertionError

在此输入图像描述

  1. 调试失败的测试,它将在Assertion.java中破坏

  2. 查看调试器并导航到要调试的测试,如下所示:

在此输入图像描述

您现在可以在测试中检查变量,计算表达式等

如果只需要在JUnit中捕获的异常,则可以在异常断点中使用“catch类过滤器”,并在JUnit中指定一个被捕获的类。

在摆弄了一段时间之后,以下似乎效果最好:“​​任何异常”使用catch类过滤器org.junit.runners.*和类过滤器-org.junit.*来删除捕获和未捕获的异常-org.junit.*捕获了JUnit机制本身抛出的异常。

捕获和未捕获的AssertionError的无条件断点似乎也是一个好主意,当断言失败时检查测试本身的局部变量中的数据。

暂无
暂无

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

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