Skip to content
This repository has been archived by the owner on May 3, 2024. It is now read-only.

Commit

Permalink
JUnit 4 to JUnit 5 migration (#344)
Browse files Browse the repository at this point in the history
* JUnit 5 (WIP)

* switch to jupiter engine

* junit5 latest

* code cleanup

* Update fahrschein-http-apache/src/test/java/org/zalando/fahrschein/http/apache/HttpComponentsRequestFactoryTest.java

Co-authored-by: Malte <[email protected]>

* Remove hamcrest-compose

* fix test

Co-authored-by: Malte <[email protected]>
  • Loading branch information
otrosien and MALPI authored Jul 5, 2022
1 parent 6133ca7 commit 83f4c3f
Show file tree
Hide file tree
Showing 30 changed files with 384 additions and 355 deletions.
16 changes: 12 additions & 4 deletions buildSrc/src/main/groovy/fahrschein.java-conventions.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ java {
}
}

test {
useJUnitPlatform()
}

tasks.withType(JavaCompile).configureEach {
options.compilerArgs << '-parameters'
options.compilerArgs << '-Xlint:all'
Expand All @@ -31,11 +35,13 @@ dependencies {
testRuntimeOnly("org.slf4j:slf4j-simple:${property('slf4j.version')}") {
because "we want the slf4j-simple logger implementation available at test runtime"
}

// JUnit 5
testImplementation("org.junit.jupiter:junit-jupiter:${property('junit.version')}")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${property('junit.version')}")
testImplementation("org.mockito:mockito-junit-jupiter:${property('mockito.version')}")
testImplementation("org.mockito:mockito-core:${property('mockito.version')}") {
because "we want mockito to be used in tests"
}
testImplementation("junit:junit:${property('junit.version')}") {
because "we want a common version JUnit across all projects"
because "We want Mockito to be used in tests"
}
testImplementation('org.hamcrest:hamcrest:2.2') {
because "we want to have hamcrest available for all testing"
Expand All @@ -49,6 +55,7 @@ configurations.all {
resolutionStrategy.dependencySubstitution {
substitute(platform(module('commons-logging:commons-logging'))).
using module("org.slf4j:jcl-over-slf4j:${property('slf4j.version')}")
// hamcrest changed package coordinates. Make sure to only include the new one.
substitute(platform(module('org.hamcrest:hamcrest-core'))).
using module("org.hamcrest:hamcrest:2.2")
}
Expand All @@ -57,6 +64,7 @@ configurations.all {
test {
finalizedBy jacocoTestReport // report is always generated after tests run
}

jacocoTestReport {
dependsOn test // tests are required to run before generating the report
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -29,6 +29,7 @@
import org.zalando.fahrschein.domain.Subscription;
import org.zalando.fahrschein.http.apache.HttpComponentsRequestFactory;
import org.zalando.fahrschein.http.api.ContentEncoding;
import org.zalando.fahrschein.http.api.Request;
import org.zalando.fahrschein.http.api.RequestFactory;
import org.zalando.fahrschein.http.jdk11.JavaNetRequestFactory;
import org.zalando.fahrschein.http.simple.SimpleRequestFactory;
Expand All @@ -55,7 +56,6 @@
/*
* Enable wire-debug by running with -Djdk.httpclient.HttpClient.log=requests
*/
@RunWith(Parameterized.class)
public class NakadiClientEnd2EndTest extends NakadiTestWithDockerCompose {

private static final Logger logger = LoggerFactory.getLogger("okhttp3.wire");
Expand All @@ -78,17 +78,8 @@ public class NakadiClientEnd2EndTest extends NakadiTestWithDockerCompose {
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}

public final RequestFactory requestFactory;

private NakadiClient nakadiClient;

public NakadiClientEnd2EndTest(RequestFactory requestFactory, String testName) {
this.requestFactory = requestFactory;
}

@Before
public void setUpNakadiClient() {
nakadiClient = NakadiClient
private NakadiClient setUpNakadiClient(RequestFactory requestFactory) {
return NakadiClient
.builder(getNakadiUrl(), requestFactory)
.withObjectMapper(objectMapper)
.build();
Expand Down Expand Up @@ -141,12 +132,14 @@ private static RequestFactory simple(ContentEncoding contentEncoding) {
return new SimpleRequestFactory(contentEncoding);
}

@Test
public void testPublish() throws IOException {
publish(UUID.randomUUID().toString());
@ParameterizedTest
@MethodSource("getRequestFactories")
public void testPublish(RequestFactory requestFactory) throws IOException {
NakadiClient nakadiClient = setUpNakadiClient(requestFactory);
publish(nakadiClient, UUID.randomUUID().toString());
}

private List<OrderEvent> publish(String testId) throws IOException {
private List<OrderEvent> publish(NakadiClient nakadiClient, String testId) throws IOException {
createEventTypes("/eventtypes", testId);
List<OrderEvent> events = IntStream.range(0, 10)
.mapToObj(
Expand All @@ -156,8 +149,10 @@ private List<OrderEvent> publish(String testId) throws IOException {
return events;
}

@Test
public void testSubscribe() throws IOException, EventAlreadyProcessedException {
@ParameterizedTest
@MethodSource("getRequestFactories")
public void testSubscribe(RequestFactory requestFactory) throws IOException, EventAlreadyProcessedException {
NakadiClient nakadiClient = setUpNakadiClient(requestFactory);
String testId = UUID.randomUUID().toString();
createEventTypes("/eventtypes", testId);
final Listener<OrderEvent> listener = subscriptionListener();
Expand All @@ -181,7 +176,7 @@ public void testSubscribe() throws IOException, EventAlreadyProcessedException {
}
return;
}));;
List<String> eventOrderNumbers = publish(testId).stream().map(e -> e.orderNumber).collect(toList());
List<String> eventOrderNumbers = publish(nakadiClient, testId).stream().map(e -> e.orderNumber).collect(toList());
// verifies that every order number that was published got consumed
for (String on: eventOrderNumbers) {
Mockito.verify(listener, timeout(10000).atLeastOnce()).accept(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,44 @@
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.zalando.fahrschein.http.api.ContentEncoding;
import org.zalando.fahrschein.http.api.Request;
import org.zalando.fahrschein.http.api.RequestFactory;
import org.zalando.fahrschein.http.test.AbstractRequestFactoryTest;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.IOException;
import java.net.SocketTimeoutException;

@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class HttpComponentsRequestFactoryTest extends AbstractRequestFactoryTest {

@Test(expected = SocketTimeoutException.class)
@Test
public void testTimeout() throws IOException {
// given
server.createContext("/timeout", exchange -> {
try {
Thread.sleep(10l);
exchange.sendResponseHeaders(201, 0);
} catch (InterruptedException e) { }
} catch (InterruptedException e) {
fail("Unexpected Exception thrown");
}
});

// when
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1).build();
final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
RequestFactory f = new HttpComponentsRequestFactory(httpClient, ContentEncoding.GZIP);
Request r = f.createRequest(serverAddress.resolve("/timeout"), "GET");
r.execute();

assertThrows(SocketTimeoutException.class, () -> {
r.execute();
});
}

public RequestFactory defaultRequestFactory(ContentEncoding contentEncoding) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package org.zalando.fahrschein.http.api;

import org.junit.Test;
import org.junit.jupiter.api.Test;

import java.util.HashSet;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;


public class ContentTypeTest {
Expand Down Expand Up @@ -33,9 +34,11 @@ public void shouldParseProblemJson() {
assertEquals("problem+json", contentType.getSubtype());
}

@Test(expected = IllegalArgumentException.class)
@Test
public void shouldFailOnIllegalContentType() {
ContentType.valueOf("foo bar");
assertThrows(IllegalArgumentException.class, () -> {
ContentType.valueOf("foo bar");
});
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package org.zalando.fahrschein.http.api;

import org.junit.Test;
import org.junit.jupiter.api.Test;

import java.util.HashSet;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class HeadersImplTest {
@Test
Expand Down Expand Up @@ -57,15 +58,17 @@ public void shouldCopyHeaders() {
assertEquals(new HashSet<>(asList("Content-Type", "Content-Length")), copy.headerNames());
}

@Test(expected = UnsupportedOperationException.class)
@Test
public void readOnlyViewShouldNotSupportAdd() {

final HeadersImpl readOnlyHeaders = new HeadersImpl(new HeadersImpl(), true);

readOnlyHeaders.add("Content-Type", "application/json");
assertThrows(UnsupportedOperationException.class, () -> {
readOnlyHeaders.add("Content-Type", "application/json");
});
}

@Test(expected = UnsupportedOperationException.class)
@Test
public void readOnlyViewShouldNotSupportPut() {
final HeadersImpl headers = new HeadersImpl();
headers.put("Content-Type", "text/plain");
Expand All @@ -74,7 +77,9 @@ public void readOnlyViewShouldNotSupportPut() {
final HeadersImpl readOnlyHeaders = new HeadersImpl(headers, true);

assertEquals("text/plain", readOnlyHeaders.getFirst("Content-Type"));
readOnlyHeaders.put("Content-Type", "application/json");
assertThrows(UnsupportedOperationException.class, () -> {
readOnlyHeaders.put("Content-Type", "application/json");
});
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package org.zalando.fahrschein.http.jdk11;

import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.zalando.fahrschein.http.api.ContentType;
import org.zalando.fahrschein.http.api.Headers;

Expand All @@ -12,8 +12,9 @@
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class JavaNetHeadersDelegateTest {

Expand Down Expand Up @@ -54,19 +55,23 @@ public void shouldReturnEmptyListForUnknownHeaders() {
assertEquals(emptyList(), headers.get(Headers.CONTENT_TYPE));
}

@Test(expected = UnsupportedOperationException.class)
@Test
public void readOnlyViewShouldNotSupportAdd() {
final Headers headers = new JavaNetHeadersDelegate(requestBuilder().build().headers());
headers.add(Headers.CONTENT_TYPE, "application/json");
assertThrows(UnsupportedOperationException.class, () -> {
headers.add(Headers.CONTENT_TYPE, "application/json");
});
}

@Test(expected = UnsupportedOperationException.class)
@Test
public void readOnlyViewShouldNotSupportPut() {
final Headers headers = new JavaNetHeadersDelegate(requestBuilder()
.setHeader(Headers.CONTENT_TYPE, "text/plain")
.setHeader(Headers.CONTENT_ENCODING, "gzip").build().headers());

headers.put(Headers.CONTENT_TYPE, "application/json");
assertThrows(UnsupportedOperationException.class, () -> {
headers.put(Headers.CONTENT_TYPE, "application/json");
});
}

@Test
Expand All @@ -80,22 +85,25 @@ public void shouldGetContentType() {
assertEquals(ContentType.TEXT_PLAIN, contentType);
}

@Test(expected = UnsupportedOperationException.class)
@Test
public void shouldNotSetContentLength() {
final Headers headers = new JavaNetHeadersDelegate(requestBuilder().build().headers());
headers.setContentLength(2000L);
assertThrows(UnsupportedOperationException.class, () -> {
headers.setContentLength(2000L);
});
}

@Test(expected = UnsupportedOperationException.class)
@Test
public void shouldNotSetContentType() {
final Headers headers = new JavaNetHeadersDelegate(requestBuilder().build().headers());
headers.setContentType(ContentType.TEXT_PLAIN);
assertThrows(UnsupportedOperationException.class, () -> {
headers.setContentType(ContentType.TEXT_PLAIN);
});
}

@Test
public void shouldReturnMinusOneForUnknownContentLength() {
final Headers headers = new JavaNetHeadersDelegate(requestBuilder().build().headers());

assertEquals(-1L, headers.getContentLength());
}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
package org.zalando.fahrschein.http.jdk11;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.zalando.fahrschein.http.api.ContentEncoding;
import org.zalando.fahrschein.http.api.Request;
import org.zalando.fahrschein.http.api.RequestFactory;
import org.zalando.fahrschein.http.test.AbstractRequestFactoryTest;

import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
import java.util.Optional;

@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class JavaNetRequestFactoryTest extends AbstractRequestFactoryTest {

@Override
public RequestFactory defaultRequestFactory(ContentEncoding contentEncoding) {
return new JavaNetRequestFactory(HttpClient.newHttpClient(), Optional.empty(), contentEncoding);
}

@Test(expected = java.net.http.HttpTimeoutException.class)
@Test
public void testTimeout() throws IOException {
// given
server.createContext("/timeout", exchange -> {
Expand All @@ -34,7 +38,7 @@ public void testTimeout() throws IOException {
// when
RequestFactory f = new JavaNetRequestFactory(HttpClient.newBuilder().build(), Optional.of(Duration.ofMillis(1)), ContentEncoding.IDENTITY);
Request r = f.createRequest(serverAddress.resolve("/timeout"), "GET");
r.execute();
assertThrows(HttpTimeoutException.class, () -> r.execute());
}

}
Loading

0 comments on commit 83f4c3f

Please sign in to comment.