JUnit Understanding JUnit Assertions and Annotations Estimated reading: 28 minutes 161 views JUnit provides a variety of assertions and annotations to facilitate effective test execution. Assertions help validate expected and actual outcomes, while annotations simplify test organization and execution flow. In this guide, Wwe will explore the different assertions and annotations available in JUnit and demonstrate their usage with practical examples.Understanding JUnit AssertionsAssertions are used to verify that expected outcomes match actual results. JUnit provides several assertion methods, including:JUnit Assertions Testimport org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class AssertionsTest { @Test void testAssertions() { assertEquals(5, 2 + 3, "Addition result should be 5"); assertTrue(3 > 1, "3 should be greater than 1"); assertFalse(2 > 5, "2 is not greater than 5"); assertNotNull("JUnit", "String should not be null"); } }Common JUnit AnnotationsJUnit annotations control test execution and setup. Some of the key annotations include: @Test: Marks a method as a test case. @BeforeEach: Runs before each test method. @AfterEach: Runs after each test method. @BeforeAll: Runs once before all test methods in the class. @AfterAll: Runs once after all test methods in the class.JUnit Annotations ExplainedJUnit provides several annotations that control test execution and setup. These annotations help in organizing and structuring test cases efficiently. Test BeforeEach AfterEach BeforeAll AfterAll @Test – Marks a Method as a Test CaseThis annotation is used to indicate that a method is a test case.JUnit will automatically execute any method annotated with @Test. Example: @Test Annotation Example@Test void testExample() { assertEquals(10, 5 + 5, "Sum should be 10"); }@BeforeEach – Runs Before Each Test MethodThis annotation is used to execute a method before each @Test method.Typically used for test setup, such as initializing test data or opening a database connection. Example: BeforeEach Annotations Example@BeforeEach void setup() { System.out.println("Setup before each test"); }If there are multiple test methods, @BeforeEach will run before every test method execution.@AfterEach – Runs After Each Test MethodThis annotation ensures that a method runs after each test method.It is commonly used for cleanup, such as closing database connections or releasing resources. Example: AfterEach Annotations Example@AfterEach void cleanup() { System.out.println("Cleanup after each test"); }If there are multiple test methods, @AfterEach will run after every test method execution.@BeforeAll – Runs Once Before All Test MethodsThis annotation is used to execute a method once before any test methods in the class.It is typically used for expensive setup operations like establishing a database connection or starting a web server.The method must be static. Example: BeforeAll Annotations Example@BeforeAll static void setupAll() { System.out.println("Runs once before all tests"); }This method runs only once per test class.@AfterAll – Runs Once After All Test MethodsThis annotation ensures that a method runs only once after all test methods have been executed.It is used for global cleanup operations like shutting down a database or stopping a web server.The method must be static. Example: AfterAll Annoations Example@AfterAll static void cleanupAll() { System.out.println("Runs once after all tests"); }This method runs only once per test class, at the very end.Using JUnit Assertions and Annotations in a Real TestThis test case automates the validation of a locked screen page. It checks whether key elements, such as the user’s name, email, password field, and unlock button, are correctly displayed and functioning as expected.LockedScreenTest class | JUnit Common Annotationspackage com.mqa.junit.tests; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; class LockedScreenTest { private WebDriver driver; @BeforeEach void setup() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "src/test/resources/driver/chromedriver"); driver = new ChromeDriver(); driver.get("https://jahmalrichard.github.io/mqa-demo-test-app/pages-lock-screen.html"); Thread.sleep(3000); } @Test void testNameIsDisplayed() { WebElement name = driver.findElement(By.className("user-name")); assertTrue(name.getText().trim().matches("John Doe"), "User name should be John Doe"); } @Test void testEmailIsDisplayed() { WebElement email = driver.findElement(By.className("user-email")); assertEquals("johndoe@okler.com", email.getText().trim(), "User email should match"); } @Test void testPasswordFieldDoesNotContainName() { WebElement passwordField = driver.findElement(By.id("pwd")); assertNotEquals("John Doe", passwordField.getAttribute("value"), "Password field should not contain the user name"); } @Test void testUnlockButtonIsPresent() { WebElement unlockButton = driver.findElement(By.className("btn-primary")); assertNotNull(unlockButton, "Unlock button should be present"); } @Test void testUnlockButtonInvalidLabel() { WebElement unlockButton = driver.findElement(By.className("btn-primary")); assertFalse(unlockButton.getAttribute("value") == "Denied", "Unlock button text should be Unlock"); } @AfterEach void teardown() { driver.quit(); } }Explanation of the Test Code @BeforeEach: Initializes the WebDriver and navigates to the locked screen page before each test runs. @Test testNameIsDisplayed(): Verifies that the user’s name is correctly displayed using contains() to avoid exact match issues. @Test testEmailIsDisplayed(): Ensures the email is displayed correctly and trims whitespace before comparing. @Test testPasswordFieldDoesNotContainName(): Confirms that the password field does not prefill the user’s name. @Test testUnlockButtonIsPresent(): Asserts that the button is not null, confirming it exists. testUnlockButtonInvalidLabel(): Asserts that its label is not "Denied", ensuring the correct button text. @AfterEach: Closes the browser after each test to free resources.ConclusionUnderstanding assertions and annotations enables you to write well-structured and maintainable test cases. Assertions ensure correctness, while annotations help manage the test lifecycle. In the next guide, we will explore Testing Exceptions in JUnit and how to verify exception handling in web applications.Tagged:JUnit JUnit - Previous Writing Your First Web Test Case with JUnit Next - JUnit Testing Exceptions in JUnit