"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Junit Date : 19/01/2025 (Session - 106) _____________________________________________________________________________________________________________________________ JUnit ====== * Unit testing framework which helps to test piece of code written project. * Developer level testing framework. JUnit 5 ======= JUnit 5 is a popular framework for writing and running tests in Java. It is the next generation of JUnit, built to take advantage of Java 8+ features, and consists of three main modules: JUnit Platform =============== * Acts as a foundation for launching testing frameworks on the JVM. * Provides a TestEngine API for developing custom testing frameworks. * Enables running tests from JUnit 5 and other test engines like Spock or Cucumber. JUnit Jupiter ============= * The main module for writing tests in JUnit 5. * Introduces new annotations and programming models. * Provides better support for parameterized tests, extensions, and more flexible lifecycle hooks. JUnit Vintage ============= * Provides backward compatibility for running JUnit 3 and JUnit 4 tests on the JUnit Platform. * Useful when migrating existing projects to JUnit 5. Annotations ============ JUnit 5 introduces new annotations that simplify testing: 1.@Test: Marks a method as a test method. 2.@BeforeEach and @AfterEach: Run before/after each test method. 3.@BeforeAll and @AfterAll: Run once before/after all test methods (must be static). 4.@DisplayName: Customizes test method names for better readability. 5.@Disabled: Disables a test or class. 6.@Nested: Creates nested test classes for better organization. 7.@Tag: Groups tests to control which are executed. Assertions ========== * assertEquals(expected, actual), assertTrue(condition), assertNotNull(object), etc. * Support for grouped and dependent assertions using assertAll. Parameterized Tests =================== * Annotations like @ParameterizedTest, @ValueSource, @CsvSource, and @MethodSource allow you to run a test with multiple inputs. Example ======= import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; class CalculatorTest { private Calculator calculator; @BeforeEach void setUp() { calculator = new Calculator(); } @Test @DisplayName("Addition works correctly") void testAddition() { assertEquals(5, calculator.add(2, 3), "2 + 3 should equal 5"); } @Test @Disabled("Not implemented yet") void testSubtraction() { // Test case to be implemented } @ParameterizedTest @ValueSource(ints = {2, 3, 5, 7, 11}) void testIsPrime(int number) { assertTrue(calculator.isPrime(number), number + " should be prime"); } @AfterEach void tearDown() { calculator = null; } } Junit Workshop ============== https://www.youtube.com/watch?v=3FutI2_Tix8 https://www.youtube.com/watch?v=UhByIkYqHcg (01:25- Mockito) https://www.youtube.com/watch?v=xL4OlQ_W3Ek https://github.com/maheshashokit/JUnit_Workshop_Apps