JUnit Assertions

T 
/**
 * INTORDUCTION TO JUNIT (Junit 4 style)
 * -------------------------------------
 * JUnit is the standard unit-testing framework for java.
 * A test method is any public method annotated with @Test.
 * 
 * Test execution:
 * - IDEs (Eclipse/ItelliJ/VSCode) detect test classes automatically
 * - Methods annotated with @Test are invoked by the test runner
 * - A single failing assertion fails the entire test method
 */

package com.minte9.junit.introduction;

import org.junit.Test;
import static org.junit.Assert.*;

public class AssertionsTest {

    @Test
    public void testBasicAssertions() {
        
        // ------------------------------
        // assertEquals(expected, actual)
        // ------------------------------
        assertEquals(4, 2 + 2);
        assertEquals("hello", "he" + "llo");

        // -------------------------------
        // assertTrue / assertFalse
        // -------------------------------
        assertTrue(10 > 1);
        assertFalse(5 > 10);

        // -------------------------------
        // assertNull / assertNotNull
        // -------------------------------
        String a = null;
        String b = "JUnit";

        assertNull(a);
        assertNotNull(b);

        // -------------------------------
        // Additional numeric assertions
        // -------------------------------
        assertEquals(3.14, 3.14, 0.0001);  // double comparison with delta
        assertEquals(3.14, 3.14, 0.1);
    }
}






Questions and answers:
Clink on Option to Answer




1. What marks a method as a test in JUnit 4?

  • a) @Test annotation
  • b) Method name starting with "test"

2. What happens if one assertion in a test method fails?

  • a) Only that line is skipped
  • b) The entire test method fails

3. What does assertEquals(expected, actual) check?

  • a) That two values are equal
  • b) That two values are different

4. What does assertTrue(condition) verify?

  • a) The condition is true
  • b) The condition is false

5. Why does assertEquals for doubles require three arguments?

  • a) To provide a delta (tolerance) for floating-point comparison
  • b) To print the value in logs

6. How do IDEs run JUnit tests?

  • a) They automatically detect test classes and methods annotated with @Test
  • b) Only when tests are executed manually via the command line


References: