And*_*kis -1 java testing junit
为任务做一些junit测试.只是想知道在同一个测试中是否可以有多个assertEquals()语句?当它通过时,这是否意味着如果一个assertEquals语句失败将会失败?或者只需要一个assertEquals()语句?
car3 = new Car("gargle", 45, false);
car4 = new Car("cheese", 45, true);
moto3 = new MotorCycle("ass", 45);
assertEquals(true, carPark.spacesAvailable(car3));
assertEquals(true, carPark.spacesAvailable(car4));
assertEquals(true, carPark.spacesAvailable(moto3));
Run Code Online (Sandbox Code Playgroud)
只会使用第一个assertEquals或将全部使用
所有断言都将按顺序运行.第一个失败的断言导致测试失败,之后没有进一步的断言.
AssertJ有一种机制,允许运行所有断言,无论它们是成功还是失败:
final SoftAssertions soft = new SoftAssertions();
soft.assertThat(...);
soft.assertThat(...);
soft.assertThat(...);
soft.assertAll();
Run Code Online (Sandbox Code Playgroud)
这将报告所有失败的断言.assertAll().链接到javadoc.
编辑从2.0.0(仅限Java 7+)开始AutoCloseableSoftAssertions,这也意味着您不需要.assertAll()最后:
try (
final AutoCloseableSoftAssertions soft
= new AutoCloseableSoftAssertions();
) {
soft.assertThat(thePope).isSaint(); // or whatever
} // <--- .assertAll() here!
Run Code Online (Sandbox Code Playgroud)