Test method naming conventions in JUnit - Build an Automation Script
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class CalculatorTest { @Test void add_TwoPositiveNumbers_ReturnsCorrectSum() { Calculator calculator = new Calculator(); int result = calculator.add(3, 5); assertEquals(8, result, "3 + 5 should equal 8"); } } class Calculator { public int add(int a, int b) { return a + b; } }
The test class CalculatorTest contains a single test method named add_TwoPositiveNumbers_ReturnsCorrectSum. This name clearly states the method under test (add), the condition (TwoPositiveNumbers), and the expected result (ReturnsCorrectSum).
The method is annotated with @Test from JUnit 5 to mark it as a test method.
Inside the test, we create an instance of Calculator and call the add method with 3 and 5. We then assert that the result is 8 using assertEquals. The assertion message helps explain the expected behavior if the test fails.
This structure follows best practices by having a descriptive method name, using proper annotations, and clear assertions.
Now add two more test methods for subtraction and multiplication following the same naming conventions.