gpt4 book ai didi

java - 如何模拟公共(public)API(第三方API)以生成spring Restdocs

转载 作者:行者123 更新时间:2023-12-01 17:49:35 25 4
gpt4 key购买 nike

我能够为我创建的剩余服务生成剩余文档,但无法为我正在使用的服务生成文档。

有没有办法测试和生成第三方 API 的文档。

我用来生成本地服务文档的示例代码。

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = RestdocApplication.class)
public class CountryDocumentation {
private static final Logger logger =
LoggerFactory.getLogger(CountryDocumentation.class);

private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;

@Rule
public final JUnitRestDocumentation restDocumentation = new
JUnitRestDocumentation("target/generated-snippets");

@Mock
private CountryService countryService;

@Mock
private RestTemplate restTemplate;

@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)
.uris().withHost("X.X.X.X").withPort(9090).and().operationPreprocessors()
.withResponseDefaults(prettyPrint())
.withRequestDefaults(prettyPrint())).defaultRequest(get("/")).build();
}

@Test
public void getCountryDefinition() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().is(200))
.andDo(document("{ClassName}/{methodName}"));
}
}

最佳答案

您在评论中说过您想要模拟对远程服务的实际调用。我认为这使得文档毫无意义。如果生成文档的测试正在调用模拟服务,那么您正在记录模拟而不是服务。如果您希望利用 REST Docs 的测试驱动方法来生成文档,那么您的测试需要调用正在记录的服务。如果该服务只能远程访问,那么您需要进行 HTTP 调用来记录它。

您可以将 Spring REST Docs 与 REST Assured 或 WebTestClient 结合使用来记录可通过 HTTP 访问的任何服务。以下是 REST Assured 的示例,其中记录了 Stack Exchange API 的一部分:

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import org.springframework.restdocs.JUnitRestDocumentation;

import static io.restassured.RestAssured.given;
import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document;
import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration;

public class RestAssuredExampleTests {

@Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();

private RequestSpecification documentationSpec;

@Before
public void setUp() {
this.documentationSpec = new RequestSpecBuilder()
.addFilter(documentationConfiguration(this.restDocumentation))
.setBaseUri("https://api.stackexchange.com/2.2").build();
}

@Test
public void answers() throws Exception {
given(this.documentationSpec).accept(ContentType.JSON).filter(document("answers"))
.when().get("answers?order=desc&sort=activity&site=stackoverflow").then()
.assertThat().statusCode(200);
}

}

关于java - 如何模拟公共(public)API(第三方API)以生成spring Restdocs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51875309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com