在测试RestClient-Implementation时,我想模拟一个RestClientException,它可能被该实现中的一些RestTemplate方法引发了删除方法:
@Override
public ResponseEntity<MyResponseModel> documentDelete(String id) {
template.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity<MyResponseModel> response = null;
try {
String url = baseUrl + "/document/id/{id}";
response = template.exchange(url, DELETE, null, MyResponseModel.class, id);
} catch (RestClientException ex) {
return handleException(ex);
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我用这种方式定义了mock-server:
@Before
public void setUp() {
mockServer = MockRestServiceServer.createServer(template);
client = new MyRestClient(template, serverUrl + ":" + serverPort);
}
Run Code Online (Sandbox Code Playgroud) 我想了解 MockServerClient( 或 org.mockserver.integration.ClientAndServer) 和 WireMockServer 这两个框架之间的区别是什么?它们可以交换吗?我阅读了文档。但无法弄清楚这两者之间有什么区别?谢谢。
我正在尝试使用wire-mock创建一个模拟服务器,但我面临以下问题:我想点击这样的URL /customers?customerId={customerId}&customerNo={customerNo}。
我的问题是如何在 Java 代码中匹配请求参数customerId和customerNo模拟服务器的存根。
编辑
第一次响应后,结果如下:
编辑2
这是我的存根:
WireMockServer mockServer = new WireMockServer(8079);
mockServer.start();
mockServer.stubFor(get(urlEqualTo("/api/loan/admin/contracts"))
.withQueryParam("status", equalTo("ACTIVE"))
.withQueryParam("cnp", equalTo("1950503410033"))
.willReturn(aResponse().withBody("Welcome to Baeldung!")));
Run Code Online (Sandbox Code Playgroud) 我在为具有完全相同的请求的多个响应设置 MockServerClient 时遇到问题。
我读到,带着对“时代”的期望,这可能会完成,但我无法使它适合我的场景。
如果您使用此 JSON 调用服务(两次):
{
"id": 1
}
Run Code Online (Sandbox Code Playgroud)
第一个响应应该是“passed true”,第二个响应“passed false”
回应1:
{
"passed":true
}
Run Code Online (Sandbox Code Playgroud)
回应2:
{
"passed":false
}
Run Code Online (Sandbox Code Playgroud)
我设置了第一个请求,但如何设置第二个请求?
import com.nice.project.MyService;
import com.nice.project.MyPojo;
import org.mockito.Mock;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.matchers.TimeToLive;
import org.mockserver.matchers.Times;
import org.mockserver.model.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.when;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static …Run Code Online (Sandbox Code Playgroud) 我的网站正在向Postman的模拟服务器发帖子.我希望能够看到我的要求,以确保它以我期望的方式出现.我已经尝试连接显示器,但这并没有向我显示我能够找到的任何地方的请求.
在Postman Windows客户端中,我可以看到一个请求进入我的Postman模拟服务器吗?
我在 Postman 中设置了一个模拟服务器。
对于请求 X,我添加了 2 个示例(响应)
当我使用x-mock-response-code 时,我能够得到适当的响应。
但是当我不使用 x-mock-response-code 时,我总是收到 400 Bad Request。我默认为 200。但它没有发生。
我需要在示例响应中添加一些东西吗?我试图将示例名称更改为默认值,但没有用。
我有以下测试:
org.springframework.test.web.client.MockRestServiceServer mockServer
Run Code Online (Sandbox Code Playgroud)
当我使用any(String.class)或确切的 URL运行时,它们运行良好:
mockServer.expect(requestTo(any(String.class)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)
或者:
mockServer.expect(requestTo("https://exact-example-url.com/path"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("response", MediaType.APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)
我希望通过字符串模式请求避免检查确切的 URL。我可以在Spring MockRestServiceServer上编写自定义匹配器来处理对同一 URI 的多个请求(自动发现)
有没有其他方法可以mockServer.expect(requestTo(".*example.*"))通过 String 模式制作?
我的 UITest 项目适用于原始 Web 服务器,但我想使用WireMock.net将其替换为模拟服务器。我已经在非 UITest 项目中成功使用了它。这是我在 UI 测试项目中的代码:
[SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}
[OneTimeSetUp]
public void InitializerOnce()
{
_mockServer = WireMockServer.Start(new WireMockServerSettings()
{
Urls = new[] { "http://localhost:12345/"},
ReadStaticMappings = true
});
_mockServer.Given(
Request.Create().WithPath("*").UsingAnyMethod())
.RespondWith(Response.Create()
.WithStatusCode(HttpStatusCode.OK).WithBody("Sample response!"));
}
[OneTimeTearDown]
public void DisposeOnce()
{
_mockServer?.Stop();
}
[Test]
public async Task Test()
{
app.Tap(c => c.Marked("MyButton"));
await Task.Delay(5000);
//Assert
Assert.IsTrue(true);
}
private WireMockServer _mockServer;
Run Code Online (Sandbox Code Playgroud)
我的主要 Android 项目有以下代码:
<Button AutomationId="MyButton" Text="Action" Clicked="Action_OnClicked"/>
private async void Action_OnClicked(object …Run Code Online (Sandbox Code Playgroud) 当我尝试使用 MockServer 模拟外部 HTTP API 时,mockserver 返回java.lang.IllegalArgumentException
这是测试代码:
new MockServerClient("localhost", 1080)
.when(request("/messages")
.withMethod("POST")
.withQueryStringParameters(
param("subject", "integration-test-subject")
)
).respond(response().withStatusCode(200));
Run Code Online (Sandbox Code Playgroud)
这是例外:
java.lang.IllegalArgumentException: Exception while parsing
[
{
"httpRequest":{
"method":"POST",
"path":"/messages",
"queryStringParameters":{
"subject":[
"integration-test-subject"
]
}
},
"httpResponse":{
"statusCode":200
},
"times":{
"remainingTimes":0,
"unlimited":true
},
"timeToLive":{
"unlimited":true
}
}
] for Expectation
Run Code Online (Sandbox Code Playgroud)
这是杰克逊的例外:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of FIELD_NAME token
at
[
Source:(String)" {
"httpRequest":{
"method":"POST",
"path":"/messages",
"queryStringParameters":{
"subject":[
"integration-test-subject"
]
}
},
"httpResponse":{
"statusCode":200
},
"times":{
"remainingTimes":0,
"unlimited":true
}, …Run Code Online (Sandbox Code Playgroud) 我的模拟服务器调度程序从未达到运行 API 28 及更高版本的模拟器上的覆盖方法,但它在其他版本上工作正常。知道如何触发它吗?还是只是API版本问题?
我指向 localhost:8080。okhttp版本是4.2.1。
fun search() {
sleepSafely(3000)
mockServer = MockWebServer()
mockServer.dispatcher = ErrorDispatcher()
mockServer.start(8080)
sleepSafely(3000)
// do the API request
}
public class ErrorDispatcher extends Dispatcher {
@NotNull
@Override
public MockResponse dispatch(RecordedRequest request) {
// never be triggered
String path = request.getPath();
if (path.equalsIgnoreCase("/api/v2/search/person")) {
return new MockResponse()
.setResponseCode(404)
.setBody("{"MOCK_KEY": "MOCK_VALUE"}");
} else if (path.equalsIgnoreCase("/api/v2/search/book")) {
return new MockResponse()
.setResponseCode(404);
} else {
return new MockResponse().setResponseCode(404);
}
}
}
Run Code Online (Sandbox Code Playgroud) 由于防火墙的原因,我们在应用程序中使用的一些 API 无法从本地开发人员计算机访问。
我想使用mockServer来模拟其中一些API,以便我们可以在本地进行开发。
运行测试时,mockServer 可以分别使用 Maven 构建阶段process-test-classes和来启动和停止verify。
当我使用 启动应用程序时如何让它运行mvn spring-boot:run ?
我有一个Orchestrator Spring Boot服务,该服务对外部服务发出几个异步的REST请求,我想模拟那些服务的响应。
我的代码是:
mockServer.expect(requestTo("http://localhost/retrieveBook/book1"))
.andExpect(method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
.body("{\"book\":{\"title\":\"xxx\",\"year\":\"2000\"}}")
.contentType(MediaType.APPLICATION_JSON));
mockServer.expect(requestTo("http://localhost/retrieveFilm/film1"))
.andExpect(method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
.body("{\"film\":{\"title\":\"yyy\",\"year\":\"1900\"}}")
.contentType(MediaType.APPLICATION_JSON));
service.retrieveBookAndFilm(book1,film1);
mockServer.verify();
Run Code Online (Sandbox Code Playgroud)
resolveBookAndFilm服务调用两种异步方法,一种方法是检索书本,另一种方法是检索电影,问题在于有时会先执行电影服务,但会出现错误:
java.util.concurrent.ExecutionException:java.lang.AssertionError:请求URI预期:HTTP://本地主机/ retrieveBook / BOOK1却被:HTTP://本地主机/ retrieveFilm / FILM1
任何想法我怎么解决这个问题,有什么类似mockito的说法,当执行此URL然后返回this或那个?
感谢和问候
我现在使用https://www.mock-server.com/的模拟服务器并在 Docker 容器中运行它。
现在我想让响应随着请求正文的变化而变化。我在官方网站上查找动态响应有一段时间了,但不知道如何从请求正文中提取特定数据。
curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
"path": "/some/path"
},
"httpResponseTemplate": {
"template": "return { statusCode: 200, body: request.body };",
"templateType": "JAVASCRIPT"
}
}'
Run Code Online (Sandbox Code Playgroud)
上面的代码是创建一个简单的期望,它将响应请求正文。例如,
$curl http://localhost:1080/some/path -d '{"name":"welly"}'
{"name":"welly"} //response
Run Code Online (Sandbox Code Playgroud)
现在我想改变回应的方式。例如,我想输入 {a:A, b:B} 并得到响应 {a:B, b:A}。
那么,如何修改request body中的json数据并交给response呢?我想有一些方法可以从json文件中提取特定数据,或者修改json数据等。另外,我想知道如何更好地搜索详细信息,因为官方网站和完整的REST API json规范(https:// app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/5.11.x#/expectation/put_expectation)对我来说很难理解。
多谢!