Junior — Middle
Какими способами вы подключаете внешние зависимости при написании тестов?
sobes.tech AI
Answer from AI
When writing tests, external dependencies are usually connected using:
-
Mock objects — using libraries such as Mockito or EasyMock to create dependency simulations, isolating the tested code.
-
Dependency Injection (DI) — dependencies are passed into the class under test via constructor or setters, allowing mocks or stubs to be substituted.
-
Using test configurations — for example, in Spring Boot, separate configurations can be created for tests where necessary dependencies are connected.
-
Integration tests with real dependencies — connecting real services or databases, often through test containers (Testcontainers).
Example with Mockito:
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
public void testGetUser() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User(1L, "John")));
User user = userService.getUser(1L);
assertEquals("John", user.getName());
}
}