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

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

如果我在任何未捕获的exception上设置了exception断点,那么这不起作用,因为JUnit捕获了exception。 如果我尝试使用catch类org.junit对捕获的exception进行断点中断,那也不起作用,因为exception在Javasreflection机制到达JUnit之前被Javasreflection机制捕获并包装。 所以我在这里有点亏本 – Eclipse只是在最初的exception停止。

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

@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时停止,这样我就可以检查导致exception的i的值。 但是,我不希望IntelliJ在neverBreakHereSinceThisIsCaught停止,因为抛出的exception没有到达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捕获的exception中断的exception断点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端内Javareflection调用的许多内部位置中断。

这就是我做的:

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

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

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

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

条件

我如何处理这个问题:

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

在此处输入图像描述

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

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

在此处输入图像描述

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

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

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

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