import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { @Test void testAdd() { assertEquals(5, 2 + 3); } @Test void testSubtract() { assertEquals(1, 3 - 2); } @Test void testMultiply() { assertEquals(6, 2 * 3); } }
Each test method uses assertEquals with correct expected and actual values. All assertions are true, so all tests pass.
assertThrows expects the exception class and a lambda that runs the code. It passes if the exception is thrown.
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class ServiceTest { private static Service service; @BeforeAll static void setup() { service = new Service(); } @Test void testServiceMethod() { assertTrue(service.isReady()); } }
In JUnit 5, methods annotated with @BeforeAll must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).
Keeping test classes in the same package as the classes they test helps with package-private access and organization. Using a separate source folder for tests keeps production and test code separate.
@BeforeEach runs before every test method to set up fresh state. @BeforeAll runs once before any tests to set up shared resources.
