我进行了测试,以查看异常是否有效,但是它不起作用。
我得到结果java.lang.AssertionError:
我希望测试抛出(exceptions.employee.IllegalBonusException
的实例和带有消息的字符串的异常,该字符串包含“ The Bonus need to <= 10.0”)
这是正常行为吗?
我以类似的代码为例,所以应该可以。
Bonus(float bonus){
validateBonusPercentage(bonus);
this.bonusPercentage = bonus;
}
public void validateBonusPercentage(float bonus) {
if (bonus > MAX_BONUS_PERCENTAGE) throw new IllegalBonusException(IllegalBonusException.TOO_BIG_BONUS);
}
@Rule
public ExpectedException ex = ExpectedException.none();
@Test
public void WHEN_BonusIsEnter_and_BonusIsSuperiorToMax_THEN_RaiseIllegalBonuslExceptionMessage() {
//Arrange
ex.expect(IllegalBonusException.class);
ex.expectMessage(IllegalBonusException.TOO_BIG_BONUS);
//Act
float tooBig = 11.00f;
//Assert
Assertions.assertThrows(IllegalBonusException.class, () -> {
this.bonus = new Bonus (tooBig);
});
}
@SuppressWarnings("serial")
public class IllegalBonusException extends IllegalArgumentException {
public static final String TOO_BIG_BONUS = "The Bonus need to be <= " + Bonus.MAX_BONUS_PERCENTAGE;
public IllegalBonusException(String s) {
super(s);
}
}
java.lang.AssertionError:预期引发的测试(exception.employee.IllegalBonusException异常和带有消息的字符串的异常,其中包含“奖金必须为<= 10.0”)
答案 0 :(得分:0)
我认为不需要同时使用undefined
和ExcepectedException
。尝试使用其中一个。例如,(假设JUnit 5):
Assertions.assertThrows
有关更多信息,请参见此SO问题:How do you assert that a certain exception is thrown in JUnit 4 tests?