Assume we have class Handler
and class Validator
. The Handler
uses Validator
to validate incoming requests.
The Validator
class is unit tested, whether returns appropriate error etc.
Later, we want to create unit tests for Handler
. The Validator
has already unit tests, so how would the test for Handler
look?
Will we write the same tests as for Validator
whether Handler
returns the appropriate error (retrieved from Validator
class)? It doesn't make sense to me.
So how would the unit test for Handler
class look in this case?
You shouldn't re-test the Validator
's logic in the Handler
's unit test.
The idea of unit (as opposed to component, integration, or end-to-end tests) is to isolate the logic of the minimal unit (usually a class) you're testing.
The textbook solution for this would be to mock the Validator
and then test that the Handler
properly reacts to different behaviors the Validator
may have.
You didn't tag the question with any programming language, but any half-decent language should have some library to allow mocking. E.g., here's how I'd do it in java using mockito and junit:
// Imports snipped for brevity's sake
@ExtendWith(MockitoExtension.class)
public class HandlerTest {
// Create a mock Validator
@Mock
private Validator validator;
private Handler handler;
// Set up the handler being tested with said validator
@BeforeEach
public void setUp() {
handler = new Handler(validator);
}
@Test
void handlePassedValidation() {
// Mock the validator with a "passing" validation
when(validator.isValid()).thenReturn(true);
handler.handle();
// Assert the handler did what it should when the validation passed
}
@Test
void handleFailedValidation() {
// Mock the validator with a "failing" validation
when(validator.isValid()).thenReturn(false);
handler.handle();
// Assert the handler did what it should when the validation failed
}
}