-1

I made a test to see if an exception works, but it doesn't work.

I get the result java.lang.AssertionError:

I expected the test to throw (an instance of exceptions.employee.IllegalBonusException and exception with message a string containing "The Bonus need to be <= 10.0")

Is that normal behavior?

I looked at similar code as an example, so this should have worked.

The main class

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);
}

The test

@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);
        }); 
}

The exception

@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: Expected test to throw (an instance of exceptions.employee.IllegalBonusException and exception with message a string containing "The Bonus need to be <= 10.0")

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

1 Answers1

0

I do not believe there is a need for using both ExcepectedException and Assertions.assertThrows. Try using one or the other. For example, (assuming JUnit 5):

@Test
public void WHEN_BonusIsEnter_and_BonusIsSuperiorToMax_THEN_RaiseIllegalBonuslExceptionMessage() {

    float tooBig = 11.00f;
    Throwable exception = Assertions.assertThrows(IllegalBonusException.class, () -> {
        this.bonus = new Bonus(tooBig);
    });
    assertEquals(IllegalBonusException.TOO_BIG_BONUS, exception.getMessage());
}

See this SO question for more information: How do you assert that a certain exception is thrown in JUnit 4 tests?

KellyM
  • 2,472
  • 6
  • 46
  • 90