Junior — Middle
What steps should be taken to eliminate class dependencies when writing a unit test?
sobes.tech AI
Answer from AI
To eliminate class dependencies when writing unit tests, the following steps are usually applied:
-
Use of interfaces or abstractions instead of concrete classes for dependencies. This allows replacing real implementations with test doubles.
-
Dependency Injection — passing dependencies through constructors, setters, or methods so that mocks or stubs can be substituted in tests.
-
Use of Mock objects with libraries like Mockito to simulate the behavior of dependencies.
-
Avoid creating dependencies directly inside the class under test (e.g., via
new), and instead obtain them from outside.
Example:
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
public String getData() {
return repository.fetchData();
}
}
// In the test
Repository mockRepo = Mockito.mock(Repository.class);
Mockito.when(mockRepo.fetchData()).thenReturn("test data");
Service service = new Service(mockRepo);
assertEquals("test data", service.getData());
Thus, the class becomes testable without depending on real implementations.