У меня есть следующий пользовательский перехватчик в моем приложении Java Spring, как показано ниже.
public class AuthInterceptor implements ClientHttpRequestInterceptor {
private final String encodedCredentials;
public AuthInterceptor(String username, String password) {
this(username, password, (Charset) null);
}
public AuthInterceptor(String username, String password, @Nullable Charset charset) {
this.encodedCredentials = HttpHeaders.encodeBasicAuth(username, password, charset);
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
headers.setBasicAuth(this.encodedCredentials);
return execution.execute(request, body);
}
}
Но я ищу документацию о том, как написать модульный тест для этого класса, и не смог найти. Любая информация о том, как тестировать, была бы действительно полезной.
Модульное тестирование этого класса так же, как и модульное тестирование любого класса.
Некоторый пример кода:
@ExtendWith(MockitoExtension.class)
public class TestAuthInterceptor
{
private AuthInterceptor classToTest;
@Mock
private ClientHttpRequestExecution mockClientHttpRequestExecution;
@Mock
private ClientHttpResponse mockClientHttpResponse;
@Mock
private HttpHeaders mockHttpHeaders;
@Mock
private HttpRequest mockHttpRequest;
@BeforeEach
public void beforeEach()
{
classToTest = new AuthInterceptor("username", "password");
}
@Test
public void intercept_allGood_success()
{
final ClientHttpResponse actualResult;
final byte[] inputBody = null;
doReturn(mockHttpHeaders).when(mockHttpRequest).getHeaders();
doReturn(mockClientHttpResponse).when(mockClientHttpRequestExecution).execute(mockHttpRequest, inputBody);
actualResult = classToTest.intercept(mockHttpRequest, inputBody, mockClientHttpRequestExecution);
assertSame(mockClientHttpResponse, actualResult);
// other asserts as desired.
}
}
Предположим, вы хотите только протестировать перехват и уже настроили mockito:
@Test
@DisplayName("Should add correct header to authorization")
void encodeProperly() throws Exception {
AuthInterceptor cut = new AuthInterceptor("someuserName","somePaswwordName");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test");
cut.intercept(request, null,null,mockedExecution );
ArgumentCaptor<HttpRequest> argumentCapture = ArgumentCaptor.forClass(HttpRequest.class) ;
verify(mockedExecution.execute(argumentCapture.capture(),any()));
assertEquals(expectedEncodedCredentials,argumentCapture.getValue().getHeaders().get(HttpHeaders.AUTHORIZATION));
}
Итак, шаги: создайте свой класс для пробного разреза
затем создайте макет MockHttpServletRequest, это будет полезно для проверки