realqmaster
5/8/2019 - 9:39 PM

WiremockJunit.java

package my.test;

import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;

import java.io.IOException;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.junit.WireMockRule;

import it.my.mfdemo.MultiformatJpaApplication;
import it.my.mfdemo.model.Country;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = MultiformatJpaApplication.class)
public class WireTest {

	@Rule
	public WireMockRule wireMockRule = new WireMockRule(9999);

	@Test
	public void countryListTest() throws ClientProtocolException, IOException {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet request = new HttpGet(String.format("http://localhost:%s/country/list", 9999));
		request.addHeader("Accept", "text/html");
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String httpResponse = httpClient.execute(request, responseHandler);

		ObjectMapper mapper = new ObjectMapper();
		List<Country> result = mapper.readValue(httpResponse, new TypeReference<List<Country>>() {
		});

		for (Country country : result) {
			System.out.println(country.getId());
		}

		httpClient.close();
		verify(getRequestedFor(urlEqualTo("/country/list")));
	}

	@Test
	public void recordables() throws ClientProtocolException, IOException {
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet request = new HttpGet(String.format("http://localhost:%s/recordables/123", 9999));
		request.addHeader("Accept", "text/html");
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String httpResponse = httpClient.execute(request, responseHandler);
		System.out.println(httpResponse);
	}

}