Verify Mockito dependency setup in a JUnit project
Preconditions (2)
✅ Expected Result: The test runs successfully without errors, indicating Mockito is correctly set up and mocks are working
import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class MockitoSetupTest { @Mock private Runnable mockRunnable; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } @Test void testMockIsInitialized() { assertNotNull(mockRunnable, "Mock should be initialized"); } }
This test class shows how to set up Mockito in a JUnit 5 project.
We import necessary classes from JUnit and Mockito.
The @Mock annotation marks mockRunnable as a mock object.
In the @BeforeEach method setUp(), we call MockitoAnnotations.openMocks(this) to initialize all mocks annotated with @Mock.
The test method testMockIsInitialized() asserts that the mock object is not null, confirming Mockito is set up correctly.
This simple test ensures the dependency is correctly added and mocks work as expected.
Add a test that mocks a List and verifies a method call
System.out.println(mockService.getData());?
import static org.mockito.Mockito.*;
public class ServiceTest {
@Test
void testGetData() {
DataService mockService = mock(DataService.class);
when(mockService.getData()).thenReturn("Mocked Data");
System.out.println(mockService.getData());
}
}import static org.mockito.Mockito.*;
public class UserServiceTest {
@Mock
UserRepository repo;
@Test
void testUser() {
when(repo.findUser()).thenReturn(new User("Alice"));
UserService service = new UserService(repo);
assertEquals("Alice", service.getUserName());
}
}Pass the test and this pattern moves unknown