Complete the code to mark the test method as independent in JUnit 5.
import org.junit.jupiter.api.Test; public class CalculatorTest { @[1] void testAddition() { // test code here } }
The @Test annotation marks a method as a test method in JUnit 5. Each test method runs independently.
Complete the code to ensure each test method runs with a fresh Calculator instance.
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class CalculatorTest { Calculator calculator; @BeforeEach void [1]() { calculator = new Calculator(); } @Test void testAddition() { // test code here } }
The method annotated with @BeforeEach runs before each test method. Naming it setup is a common convention.
Fix the error in the test method to ensure test independence by avoiding shared state.
import org.junit.jupiter.api.Test; public class CounterTest { static int count = 0; @Test void testIncrement() { count++; assertEquals(1, [1]); } }
The test checks the static variable count. Using count directly is correct. However, static state causes tests to depend on each other, which is bad practice.
Fill both blanks to create independent tests by resetting shared state before each test.
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SharedResourceTest { static int resourceCount = 0; @BeforeEach void [1]() { resourceCount = [2]; } @Test void testOne() { resourceCount++; assertEquals(1, resourceCount); } @Test void testTwo() { resourceCount += 2; assertEquals(2, resourceCount); } }
The @BeforeEach method named reset sets resourceCount to 0 before each test, ensuring tests do not affect each other.
Fill all three blanks to write independent tests using instance variables and proper setup.
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class BankAccountTest { BankAccount [1]; @BeforeEach void [2]() { [1] = new BankAccount(); } @Test void testDeposit() { [1].deposit(100); assertEquals(100, [1].getBalance()); } }
Using an instance variable account and initializing it in a setup method before each test ensures tests are independent and do not share state.