Last active
March 1, 2018 00:57
-
-
Save LenarBad/a80b1414c1ad44b915efc6b3a646748a to your computer and use it in GitHub Desktop.
Usage in Tests - Http Client with Apache Http Components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
See also