Lesson-4-JUnit5 Test Case
Lesson-4-JUnit5 Test Case
• A Unit test is a type of software test that focuses on verifying the correctness of a single unit
of code (such as a method or function) in isolation.
• JUnit is a widely used unit testing framework for Java that helps in writing and running
automated tests.
• Supports automated testing to detect issues early and reduce manual errors.
• Plays a key role in Test-Driven Development (TDD) by enabling tests to be written before
the actual implementation.
• Ensures code reliability, correctness, and maintainability by catching defects at the unit
level.
• Reduces debugging time by providing clear test reports on what works and what fails.
• Enhances team collaboration by ensuring consistent and reusable test cases for code
verification.
Annotation Description
@Test Marks a method as a test case.
@BeforeEach Runs before each test case. Used for setup.
@AfterEach Runs after each test case. Used for cleanup.
@BeforeAll Runs once before all tests (static method).
@AfterAll Runs once after all tests (static method).
@Disabled Skips a test case temporarily.
Assertion Methods
Method Purpose
assertEquals(expected, actual) Checks if values are equal.
assertTrue(condition) Passes if the condition is true.
assertFalse(condition) Passes if the condition is false.
assertNotNull(object) Ensures the object is not null.
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@BeforeEach
void setUp() {
System.out.println("Setting up a new BankAccount with $100
balance.");
account = new BankAccount(100); // Initialize before each test
}
@AfterEach
void tearDown() {
System.out.println("Test completed. Cleaning up...");
}
@Test
void testDeposit() {
account.deposit(50);
assertEquals(150, account.getBalance(), "Balance should be 150 after
deposit of 50");
}
@Test
void testWithdraw() {
account.withdraw(40);
// Before executing this test-case balance changed to 100
assertEquals(60, account.getBalance(), "Balance should be 60 after
withdrawal of 40");
}
// Check this part after Lesson-12 Exception Handling
}