WireMock와 스프링 MVC 시뮬레이터

WireMock와 스프링 MVC 시뮬레이터

봄 클라우드 계약 클래스는 편리하고, JSON WireMock의 봄 스텁에로드 할 수 제공  MockRestServiceServer. 다음은 그 예이다 :

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class WiremockForDocsMockServerApplicationTests {

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private Service service;

	@Test
	public void contextLoads() throws Exception {
		// will read stubs classpath
		MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
				.baseUrl("http://example.org").stubs("classpath:/stubs/resource.json")
				.build();
		// We're asserting if WireMock responded properly
		assertThat(this.service.go()).isEqualTo("Hello World");
		server.verify();
	}
}

baseUrl모든 아날로그 전화의 앞에 stubs()있어서의 인수로서 스터브 자원 경로 모드. 따라서,이 예에서, /stubs/resource.json스터브는 정의 경우, 아날로그 서버에로드 RestTemplate필요한 액세스 http://example.org/그것은 선언 응답을 얻을 것이다. 스텁은 나 (위의 예에서) 고정 된 파일 이름 ( ".json"모든 재귀의 목록) 디렉토리, 또는 개미 스타일 패턴있을 수 있습니다 각각의 여러 모드를 지정할 수 있습니다. JSON의 형식은 WireMock 웹 사이트에서 읽을 수있는, 보통의 WireMock 형식입니다.

Wiremock 자체 부두 (현재 9.2)의 특정 버전에 대한 "기본"지원을하고있는 동안 현재, 우리는, 봄 부팅 임베디드 서버로 톰캣, 부두 및 물러을 지원합니다. 로컬 부두를 사용하려면 기본 스레드 의존성, 그리고 봄 부팅 컨테이너의 배제 (있는 경우)를 추가해야합니다.

사용 RestDocs는 스텁을 생성

봄 RestDocs이 는 HTTP API 문서 (예를 들어, asciidoctor 형식) 봄 MockMvc 또는 RESTEasy가를 갖는 생성 할 수 있습니다. API 문서를 생성하는 동안, 당신은 또한 봄 클라우드 계약 WireMock이 WireMock 스텁을 생성 할 수 있습니다. 그냥 일반 RestDocs 테스트 케이스를 작성하고 사용 @AutoConfigureRestDocsrestdocs 출력 디렉토리에 자동으로 저장 스텁에. 예를 들면 :

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureRestDocs(outputDir = "target/snippets")
@AutoConfigureMockMvc
public class ApplicationTests {

	@Autowired
	private MockMvc mockMvc;

	@Test
	public void contextLoads() throws Exception {
		mockMvc.perform(get("/resource"))
				.andExpect(content().string("Hello World"))
				.andDo(document("resource"));
	}
}

이 시험에서 스터브 WireMock "타겟 / 단편 / 스텁 / resource.json 생성한다 ". 그것은 모든 경로와 일치하는 "/ 자원을"요청을 GET.

다른 구성은,이 모든 최초의 "호스트"와 "콘텐츠 길이"를 제외하고 스텁 정규 요청과 HTTP 방법을 만들 수 없습니다. 더 정확하게 POST의 몸을 일치하거나 넣어, 예를 들어, 요청과 일치하기 위해, 우리는 명확한 요청 정규 표현을 작성해야합니다. 1) 유일한 방법은 사용자가 지정하는 일치하는 스텁을 생성하고, 2) 요청 어설 테스트 케이스가 같은 조건에 일치하는이 두 가지 작업을 수행합니다.

주요 진입 점은 WireMockRestDocs.verify()당신이 대체 할 수 document()있는 편리한 방법을. 예를 들면 :

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureRestDocs(outputDir = "target/snippets")
@AutoConfigureMockMvc
public class ApplicationTests {

	@Autowired
	private MockMvc mockMvc;

	@Test
	public void contextLoads() throws Exception {
		mockMvc.perform(post("/resource")
                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
				.andExpect(status().isOk())
				.andDo(verify().jsonPath("$.id")
                        .stub("resource"));
	}
}

유효한 POST 및 "ID"필드는이 테스트에서 같은 응답을 얻을 것이다 : 그래서이 계약은 말을하는 것입니다. 당신은 전화에 연결할 수 있습니다 .jsonPath()다른 정규 표현을 추가 할 수 있습니다. 경우  당신이하지 않은 JayWay 문서에 익숙 하여 JSON 경로를 단축 할 수 있습니다.

또한 요청을 사용하는 대신, 생성 된 스텁과 일치하는지 여부를 확인하기 위해 WireMock API를 사용할 수 있습니다 jsonPathcontentType방법. 예 :

@Test
public void contextLoads() throws Exception {
	mockMvc.perform(post("/resource")
               .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
			.andExpect(status().isOk())
			.andDo(verify()
					.wiremock(WireMock.post(
						urlPathEquals("/resource"))
						.withRequestBody(matchingJsonPath("$.id"))
                       .stub("post-resource"));
}

당신이 정규 표현식 헤더 파일과 JSON 경로, 쿼리 매개 변수 및 요청 본문과 일치 할 수 있으므로이 매개 변수의 넓은 범위와 스텁을 만드는 데 사용할 수 있습니다 - WireMock API는 풍부하다. 위의 예는 이러한 스터브를 생성한다 :

resource.json 후
{
  "request" : {
    "url" : "/resource",
    "method" : "POST",
    "bodyPatterns" : [ {
      "matchesJsonPath" : "$.id"
    }]
  },
  "response" : {
    "status" : 200,
    "body" : "Hello World",
    "headers" : {
      "X-Application-Context" : "application:-1",
      "Content-Type" : "text/plain"
    }
  }
}
주의
당신이 사용할 수있는 wiremock()방법 또는를 jsonPath()하고 contentType()있지만 두 가지 요청 정규 방법을 만들 수 있습니다.

상기 생성 된 소비 상정는 resource.json위의 사용 포함 스텁 생성하는 다양한 방법을 사용할 수 WireMock 클래스 경로에 사용될 수있는 @AutoConfigureWireMock(stubs="classpath:resource.json")설명.

추천

출처www.cnblogs.com/borter/p/11763042.html