🌟 Day 9 of #100DaysOfCode: Mastering Advanced JUnit Features! 🌟

Hey Invaders! 👽

#100DaysOfCode day 9, I continued working on my JUnit course and dived into some advanced topics. Today, I learned about assertThrows, which helps in writing tests where an exception is expected. Here's a quick overview of today's learning:

  • assertThrows:

    • Used to test if a specific exception is thrown by the code.

        @DisplayName("Division By Zero")
        @Test
        void testIntegerDivision_WhenDividendIsDividedByZero_ShouldThrowArithmethicException(){
            System.out.println("Runing Division By Zero");
            //Arrange
            int dividend = 4;
            int divisor = 0;
            String expectedMessage = "/ by zero";
            //Act & Assert
           ArithmeticException actualMessage= assertThrows(ArithmeticException.class, () -> {
                    calculator.integerDivision(dividend, divisor);
            }, "Division by zero should have thrown arithmetic exception ");
            //Assert
            assertEquals(expectedMessage, actualMessage.getMessage());
        }

@ParameterizedTest:

  • Run the same test multiple times with different parameters.

  • @MethodSource: Supplies method arguments.

  • @CsvSource: Provides arguments directly in the annotation.

  • @CsvFileSource: Supplies arguments from a CSV file.

  • @ValueSource: Supplies a single array of values.

  • Repeated Tests: Repeat the same test a specified number of times.

This course is expanding my testing toolkit significantly! Here's some more snippets demonstrating these concepts:

@MethodSource - inside of your test class you would create a method with the same name as your test and the Stream of Arguments would be used within your test

 @DisplayName("Test integer subtraction [minuend, subtrahend, expectedResult]")
    @ParameterizedTest
    @MethodSource()
    void integerSubtraction(int minuend, int subtrahend, int expectedResult){
        //Arrange
System.out.println("Running Test " +minuend+ "-" + subtrahend + "= " + expectedResult);
        //Act
        int actualResult = calculator.integerSubtraction(minuend,subtrahend);
        //Assert
        assertEquals(expectedResult, actualResult,
                ()->
            minuend + "-" + subtrahend + " did not produce "+ expectedResult
                );
    }

private static Stream<Arguments> integerSubtraction(){
        return Stream.of(
                Arguments.of(33,1,32),
                Arguments.of(24,1,23),
                Arguments.of(54,1,53)

        );
}

@CsvSource

 @DisplayName("Test integer subtraction [minuend, subtrahend, expectedResult]")
    @ParameterizedTest
    @CsvSource({"33,1,32","24,1,23"}) <- different annotation
    void integerSubtraction(int minuend, int subtrahend, int expectedResult){
 // SAME IMPLEMENTATION AS ABOVE
    }

@CsvFileSource

 @DisplayName("Test integer subtraction [minuend, subtrahend, expectedResult]")
    @ParameterizedTest
     @CsvFileSource(resources = "/integerSubtraction.csv") <- different annotation
    void integerSubtraction(int minuend, int subtrahend, int expectedResult){
 // SAME IMPLEMENTATION AS ABOVE
    }

@ValueSource

   @ParameterizedTest
   @ValueSource(strings={"John", "Kate", "Mary"})
    void valueSourceDemonstration(String firstName){
        System.out.println(firstName);
        assertNotNull(firstName);
    }

Repeated Tests

class DemoRepeatedTest {
    Calculator calculator;
    @BeforeEach
    void beforeEachTestMethod(){
        calculator = new Calculator();
        System.out.println("Executing @BeforeEach method");
    }
    @DisplayName("Division By Zero")
    @RepeatedTest(value = 3, name ="{displayName}. Repetition {currentRepetition} of " + "{totalRepetitions}")
    void testIntegerDivision_WhenDividendIsDividedByZero_ShouldThrowArithmethicException(
            RepetitionInfo repetitionInfo,
            TestInfo testInfo){

        System.out.println("Running " +testInfo.getTestMethod().get().getName() );

        System.out.println("Repetition number:" + repetitionInfo.getCurrentRepetition() + " of " + repetitionInfo.getTotalRepetitions());
        //Arrange
        int dividend = 4;
        int divisor = 0;
        String expectedMessage = "/ by zero";
        //Act & Assert
        ArithmeticException actualMessage= assertThrows(ArithmeticException.class, () -> {
            calculator.integerDivision(dividend, divisor);
        }, "Division by zero should have thrown arithmetic exception ");

        //Assert
        assertEquals(expectedMessage, actualMessage.getMessage());
    }
}

Follow my journey on GitHub for more updates and code snippets: avrubio/JUnitUdemyCourse.

Keep coding, keep conquering! 💪

Reply

or to participate.