模拟服务器请求未找到

huangapple go评论84阅读模式
英文:

Mockserver Request not found

问题

我目前正在尝试创建期望并通过 mockServer 进行验证(可以在此处找到)。

  [1]: https://mock-server.com

我已经多次阅读了他们的文档,但我无法找出为什么我的期望验证失败。这是我的代码:

@Rule
public MockServerRule mockServerRule = new MockServerRule(this, 9000);

private MockServerClient mockServer;

@Test
public void testVerification() {
    mockServer.when(
        HttpRequest.request()
            .withMethod("POST")
            .withPath("/validate")
            .withHeader("\"Content-type\"", "\"application/json\"")
            .withBody("{username: 'foo', password: 'bar'}"))
        .respond(
            HttpResponse.response()
                .withStatusCode(401)
                .withHeaders(
                    new Header("Content-Type", "application/json; charset=utf-8"),
                    new Header("Cache-Control", "public, max-age=86400"))
                .withBody("{ message: 'incorrect username and password combination' }")
                .withDelay(TimeUnit.SECONDS, 1)
        );

    mockServer.verify(
        HttpRequest.request()
            .withMethod("POST")
            .withPath("/validate")
            .withBody("{username: 'foo', password: 'bar'}"),
        VerificationTimes.exactly(1));
}

尝试验证时,我总是收到以下错误:

java.lang.AssertionError: Request not found exactly once, expected: {
  "method" : "POST",
  "path" : "/validate",
  "body" : "{username: 'foo', password: 'bar'}"} but was:<>
	at org.mockserver.client.server.MockServerClient.verify(MockServerClient.java:267)
	at it.HttpTest.testVerification(HttpTest.java:61)
	...
英文:

I am currently trying to create expectations and get them verified by mockServer (can be found here).

I've read their documentation several times now but I can't find out why the verifcation of my expectation fails.
This is my code

    @Rule
	public MockServerRule mockServerRule = new MockServerRule(this, 9000);

	private MockServerClient mockServer;

    @Test
	public void testVerification() {
		mockServer.when(
	            HttpRequest.request()
	              .withMethod(&quot;POST&quot;)
	              .withPath(&quot;/validate&quot;)
	              .withHeader(&quot;\&quot;Content-type\&quot;, \&quot;application/json\&quot;&quot;)
	              .withBody(&quot;{username: &#39;foo&#39;, password: &#39;bar&#39;}&quot;))
	              .respond(
	                  HttpResponse.response()
	                    .withStatusCode(401)
	                    .withHeaders(
	                      new Header(&quot;Content-Type&quot;, &quot;application/json; charset=utf-8&quot;),
	                      new Header(&quot;Cache-Control&quot;, &quot;public, max-age=86400&quot;))
	                    .withBody(&quot;{ message: &#39;incorrect username and password combination&#39; }&quot;)
	                    .withDelay(TimeUnit.SECONDS,1)
	                );

        mockServer.verify(HttpRequest.request().withMethod(&quot;POST&quot;)
		          .withPath(&quot;/validate&quot;)
		          .withBody(&quot;{username: &#39;foo&#39;, password: &#39;bar&#39;}&quot;),
		        VerificationTimes.exactly(1));
	}

When trying to verify, I always get the error

java.lang.AssertionError: Request not found exactly once, expected:&lt;{
  &quot;method&quot; : &quot;POST&quot;,
  &quot;path&quot; : &quot;/validate&quot;,
  &quot;body&quot; : &quot;{username: &#39;foo&#39;, password: &#39;bar&#39;}&quot;}&gt; but was:&lt;&gt;
	at org.mockserver.client.server.MockServerClient.verify(MockServerClient.java:267)
	at it.HttpTest.testVerification(HttpTest.java:61)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.mockserver.junit.MockServerRule$1.evaluate(MockServerRule.java:107)
	at org.junit.rules.RunRules.evaluate(RunRules.java:20)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

答案1

得分: 2

好的,以下是翻译好的部分:

你忘记向模拟服务器发送请求。你只模拟了它的行为,然后检查服务器是否被调用,但你错过了调用。

尝试使用类似这样的代码:

public int callValidateUrl() throws IOException {
    URL url = new URL("http://localhost:9000/validate");

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");

    con.setDoOutput(true);
    String jsonInputString = "{username: 'foo', password: 'bar'}";
    try (OutputStream os = con.getOutputStream()) {
        byte[] input = jsonInputString.getBytes("utf-8");
        os.write(input, 0, input.length);
    }

    return con.getResponseCode();
}

如果你正在使用 Spring,使用 RestTemplate 更加简单。

英文:

Well, you forgot to send a request to your mock server. You only mocked its behaviour and then you check if the server has been called, but you missed the call.

Try it with something like this:

public int callValidateUrl() throws IOException {
    URL url = new URL(&quot;http://localhost:9000/validate&quot;);

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod(&quot;POST&quot;);
    con.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json&quot;);

    con.setDoOutput(true);
    String jsonInputString = &quot;{username: &#39;foo&#39;, password: &#39;bar&#39;}&quot;;
    try (OutputStream os = con.getOutputStream()) {
        byte[] input = jsonInputString.getBytes(&quot;utf-8&quot;);
        os.write(input, 0, input.length);
    }

    return con.getResponseCode();
}

If you are using Spring, RestTemplate is easier to use.

huangapple
  • 本文由 发表于 2020年9月11日 16:39:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63843619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定