我有一个 spring-boot 应用程序,它使用 webclient 调用一些第三方 URL(比如说http://example.com/someUri
)(我已经使用 application-dev.properties 在我的应用程序中注入这个 url 以实现松散耦合)并消耗响应并在我的应用程序中使用它.
这是我第一次为 webclient 编写测试用例。我在那里使用了@SprintBootTest。我发现有两种方法可以通过模拟 api 调用并使其调用我的本地 url(将使用 url(http://localhost:{portNumber}/someUri) 来测试我的 webclient 与第三方 Api 调用来自我的测试属性文件:src/test/resources/application.properties),它将提供一些 mockedResponse 作为对我真实客户的回报:
- 使用线模
- 使用MockWebServer
考虑上面的代码以更好地理解:
@Service
Class SampleService{
@Value("${sample.url}")
private String sampleUrl;
public String dummyClient() {
String sample =webClient.get()
.uri(sampleUrl)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.retrieve()
.bodyToMono(String.class)
.block();
return sample;
}
}
应用程序-dev.properties:
sample.url:http://example.com/someUri
src/test/resources/application.properties:
http://localhost:8090/someUri
测试类:
@SpringBootTest
public class sampleTestingClass {
@Autowired
private SampleService sampleService;
@Value("${sample.url}")
private String sampleUrl;
public static MockWebServer mockWebServer = new MockWebServer();
@BeforeAll
static void setUp() throws IOException {
mockWebServer.start(8090);
}
@AfterAll
static void tearUp() throws IOException {
mockWebServer.close();
}
HttpUrl url = mockWebServer.url("/someUri");
mockWebServer
.enqueue(
new MockResponse()
.setResponseCode(200)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("Sample Successful"));
String sample = sampleService.dummyClient();
assertEquals(sample ,matches("Sample Successful"));
}
}
但这段代码不起作用。它给了我以上错误:
java.lang.NullPointerException
如果有人知道如何解决此问题以使用模拟 URL 实现我的单元测试,那将非常有帮助?提前致谢!