Introduction
The @Test annotation tells JUnit which methods are test cases. It helps run tests automatically without manual calls.
The @Test annotation tells JUnit which methods are test cases. It helps run tests automatically without manual calls.
@Test
public void testMethodName() {
// test code here
}The method annotated with @Test must be public and void.
No arguments are allowed in the test method.
@Test
public void additionTest() {
int sum = 2 + 3;
assertEquals(5, sum);
}@Test
public void stringTest() {
String text = "hello";
assertNotNull(text);
}This test class has one test method multiplyTest that checks if 4 times 5 equals 20.
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test public void multiplyTest() { int result = 4 * 5; assertEquals(20, result); } }
Use @Test to mark each test method clearly.
JUnit 5 uses org.junit.jupiter.api.Test package.
Assertions like assertEquals help verify expected results inside @Test methods.
@Test marks methods as test cases for JUnit to run.
Test methods must be public, void, and take no parameters.
Use assertions inside @Test methods to check results.
@Test annotation in JUnit?@Test@Test annotation tells JUnit which methods are test cases to execute.@Test marks test methods [OK]@Test means 'run this method as test' [OK]@Test changes method visibility@Test with import statements@Test sets return type@Test?import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class SampleTest {
@Test
public void checkSum() {
int result = 2 + 3;
assertEquals(5, result);
}
}assertEquals(5, result) will pass.import org.junit.jupiter.api.Test;
public class ErrorTest {
@Test
private void testHidden() {
// test code
}
}@Test for this purpose in JUnit 5?assertThrows() inside @Test methods to check exceptions.@Test(expected = Exception.class) annotation parameter is from JUnit 4 and invalid in JUnit 5. Add throws Exception to the test method signature only declares exception, not tests it. Write a try-catch block without @Test misses @Test.@Test with assertThrows() inside the method -> Option D@Test(expected=) in JUnit 5@Test annotationPass the test and this pattern moves unknown