考虑我有一种测试方法,可能有副作用(例如在文件系统上创建的文件),并且可能会引发异常。即使抛出异常,也可以观察(和测试)某些副作用。我的示例测试代码如下:final SoftAssertions softly = new SoftAssertions();try { /* * May throw an exception */ doSmth();} catch (final IOException ioe) { /* * How do I add a soft assertion wrapping an exception? */}/* * Testing for side effects. */softly.assertThat(...).as("%s exit code", ...).isEqualTo(0);softly.assertThat(...).as("the number of downloaded files").isEqualTo(3);softly.assertThat(...).as("this should be true").isTrue();softly.assertThat(...).as("and this should be true, too").isTrue();softly.assertAll();问题1从抛出的异常中创建另一个软断言的最佳方法是什么?使用原始的TestNG API,我可以简单地编写softly.fail(ioe.toString(), ioe);但是AssertJ似乎没有提供任何类似的东西。到目前为止,我最好的选择是在catch块中添加以下内容:softly.assertThat(true).as(ioe.toString()).isFalse();有更好的选择吗?问题2如何使正在测试的代码引发的异常显示为结果AssertionError的原因(或抑制的异常)?目前,我执行以下操作:Throwable failure = null;try { doSmth();} catch (final IOException ioe) { failure = ioe;}try { softly.assertAll();} catch (final AssertionError ae) { if (failure != null) { if (ae.getCause() == null) { ae.initCause(failure); } else { ae.addSuppressed(failure); } } throw ae;}-但更优雅的版本值得赞赏。 最佳答案 对于问题1,Xaero的建议效果很好。但是,要解决两个问题,请尝试将catchThrowable与fail(String failureMessage, Throwable realCause)(或one for soft assertions)结合使用。如果您捕获了一个非null的throwable(这意味着被测试的代码确实抛出了异常),则可以使用fail生成带有自定义错误消息的AssertionError,并将捕获的异常作为。代码如下:Throwable thrown = catchThrowable(() -> { doSmth(); });if (thrown != null) { softly.fail("boom!", thrown);} else { softly.assertThat(...).as("%s exit code", ...).isZero(); softly.assertThat(...).as("the number of downloaded files").isEqualTo(3); softly.assertThat(...).as("this should be true").isTrue(); softly.assertThat(...).as("and this should be true, too").isTrue();}上面的代码使我有些不舒服,因为它正在测试两种不同的情况,一种情况是抛出异常,而另一种则没有异常。创建两个测试用例可能是一个好主意,这将简化测试和断言部分(我相信)。无论如何,希望对您有所帮助!ps:请注意,您可以使用AssertionError代替isZero()
08-28 21:01