Skip to content

Instantly share code, notes, and snippets.

@LenarBad
Last active March 1, 2018 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenarBad/a80b1414c1ad44b915efc6b3a646748a to your computer and use it in GitHub Desktop.
Save LenarBad/a80b1414c1ad44b915efc6b3a646748a to your computer and use it in GitHub Desktop.
Usage in Tests - Http Client with Apache Http Components
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import io.lenar.examples.spring.TestNGWithSpringApplication;
import io.lenar.examples.spring.http.HttpClient;
import io.lenar.examples.spring.model.Book;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
import com.google.gson.Gson;
@SpringBootTest(classes = TestNGWithSpringApplication.class)
public class HttpClientExampleIT extends AbstractTestNGSpringContextTests {
@Autowired
HttpClient http;
private Gson gson = new Gson();
private String serviceUrl = "https://lenar-book-service-example.com/books";
@Test
public void useAllEndpointsTest() throws IOException {
HttpResponse postResponse = http.post(serviceUrl, new Book("Title", "Author"));
Book createdBook = gson.fromJson(getContent(postResponse), Book.class);
String id = createdBook.getId();
HttpResponse getResponse = http.get(serviceUrl);
List<Book> getBooks = Arrays.asList(gson.fromJson(getContent(getResponse), Book[].class));
Book getCreatedBook = getBooks.stream()
.filter(book -> id.equals(book.getId())).findAny().orElse(null);
Book forUpdateBook = new Book("Title1", "Author1");
HttpResponse updateResponse = http.put(serviceUrl + "/" + id, forUpdateBook);
Book updatedBook = gson.fromJson(getContent(updateResponse), Book.class);
HttpResponse getUpdatedResponse = http.get(serviceUrl + "/" + id);
Book getUpdatedBook = gson.fromJson(getContent(getUpdatedResponse), Book.class);
HttpResponse deleteResponse = http.get(serviceUrl + id);
}
private String getContent(HttpResponse response) throws IOException {
return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment