🌟 Day 8 of #100DaysOfCode: Mastering JUnit with Given, When, Then 🌟

Hey Invaders πŸ‘½

#100DaysOfCode day 8, I continued working on my JUnit course and discovered a new way to organize my tests using the Given, When, Then format! I also learned a common naming practice for tests: test<System Under Test>_<Condition or StateChange>_<Expected Result>. Here's a quick breakdown of today's lessons:

  • Unit Lifecycle Methods:

    • @BeforeAll: Set up resources before all tests.

    • @AfterAll: Clean up resources after all tests.

    • @BeforeEach: Prepare setup before each test to reduce code duplication.

    • @AfterEach: Clean up resources after each test, such as closing database connections or removing test records.

  • Annotations:

    • @DisplayName: Use this to write prettier test names that show up in your test runner window.

This course is proving to be incredibly helpful in structuring my tests more effectively! Here’s a snippet demonstrating these concepts:

@DisplayName("Test Math Operations in Calculator Class")
class CalculatorTest {
    Calculator calculator;

    @BeforeAll
    static void setUp(){
        System.out.println("executing @BeforeAll method.");
    }

    @AfterAll
    static void cleanUp(){
        System.out.println("Executing @AfterAll Method");
    }

    @BeforeEach
    void beforeEachTestMethod(){
        calculator = new Calculator();
        System.out.println("Executing @BeforeEach method");
    }

    @AfterEach
    void afterEachTestMethod(){
        System.out.println("Executing @AfterEach method");
    }
    @DisplayName("Test 4/2 = 2")
    @Test
    void testIntegerDivision_WhenFourIsDividedByTwo_ShouldReturnTwo(){
        //Arrange // GIVEN that we have these preconditions
        int dividend = 4;
        int divisor =2;
        int expectedResult = 2;
        //Act //WHEN use these conditions and invoke our method
        int actualResult = calculator.integerDivision(dividend,divisor);
        //Assert //THEN the following should be true
        assertEquals(expectedResult, actualResult, "Integer division did not produce expected result");
    }
}

πŸ‘©β€πŸ’» Let’s Connect: Have you started your journey with JUnit Testing? Share your experiences and insights! Let's empower each other on this coding adventure. πŸ’¬πŸ€

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

#100DaysOfCode #JUnitTesting #JavaDevelopment #CodingJourney #TechCommunity #ContinuousLearning #GrowthMindset #SoftwareTesting

Reply

or to participate.