Verify addition method returns correct sum
Preconditions (2)
✅ Expected Result: The test passes confirming that add(2, 3) returns 5
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class Calculator { int add(int a, int b) { return a + b; } } public class CalculatorTest { @Test void testAdd() { Calculator calculator = new Calculator(); int result = calculator.add(2, 3); assertEquals(5, result, "2 + 3 should equal 5"); } }
This code defines a simple Calculator class with an add method that sums two integers.
The CalculatorTest class contains a test method testAdd annotated with @Test, which JUnit 5 uses to identify test methods.
Inside testAdd, we create a Calculator instance, call add(2, 3), and store the result.
We then use assertEquals to check if the result is 5. If it is, the test passes; otherwise, it fails.
This structure follows best practices by keeping the test focused, using clear naming, and proper JUnit 5 annotations and assertions.
Now add data-driven testing with 3 different input pairs for the add method
@Test?@Test annotation@Test annotation marks a method as a test method in JUnit, meaning it will be run to check code behavior.@Test marks test methods [OK]@Test annotation to mark a method as a test.assertEquals(expected, actual). @Test public void testMethod() { assertEquals(5, 2 + 3); } matches this.import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class SampleTest {
@Test
void additionTest() {
assertEquals(10, 5 + 5);
}
}import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalcTest {
@Test
public void testSum() {
int result = 2 + 2;
assertEquals(5, result);
}
}multiply(int a, int b) returns 0 when one input is 0. Which test method is correct?@Test and return void. @Test public void testMultiplyZero() { assertEquals(0, multiply(0, 5)); } meets this.assertEquals(0, multiply(0, 5)), which is correct.Pass the test and this pattern moves unknown