简体   繁体   English

使用 Mockito 时验证空行失败

[英]When using Mockito verify failing on empty row

Tried to test my client with this following test:尝试使用以下测试来测试我的客户端:

private static final HttpPost EXPECTED_POST = new HttpPost(someURI);

    @Test
    public void sendingPostRequest() throws IOException {
        classUnderTest.takeParamsAndSend(REQUEST_STRING);
        verify(client).execute(EXPECTED_POST);
        verifyNoMoreInteractions(client);
    }

And in the production code it's something like this:在生产代码中,它是这样的:

URI uri = createURI();
HttpPost post = new HttpPost(uri);
return client.execute(post);

The result is a "Comparison Failure" on the same execute and on the actual, there is an empty row.结果是在同一个执行和实际中出现“比较失败”,有一个空行。 Looks something like this: expected:看起来像这样:预期:

"client.execute(
    POST somePostRequest HTTP/1.1
);"

actual:实际的:

"client.execute(
   POST somePostRequest HTTP/1.1
);
"

edit: as stated in comments, most Apache HTTP client API classes does not override java.lang.Object#equals , hence you cannot reliably use org.mockito.ArgumentMatchers#eq(T) .编辑:如评论中所述,大多数 Apache HTTP 客户端 API 类不会覆盖java.lang.Object#equals ,因此您不能可靠地使用org.mockito.ArgumentMatchers#eq(T) You will want to use org.mockito.ArgumentMatchers#argThat matcher, defining your equality condition in the predicate.您将需要使用org.mockito.ArgumentMatchers#argThat匹配器,在谓词中定义您的相等条件。

Here is how I tested it:这是我测试它的方法:

import static org.mockito.ArgumentMatchers.argThat;

//...
@Test
  void stackOverflow64222693() {

    // Given
    HttpClient client = mock(HttpClient.class);
    URI        uri    = URI.create("https://stackoverflow.com/questions/64222693");
    HttpPost   post   = new HttpPost(uri);

    // When
    client.execute(post);

    // Then
    URI      expectedUri  = URI.create("https://stackoverflow.com/questions/64222693");
    HttpPost expectedPost = new HttpPost(expectedUri);

    verify(client).execute(argThat(argument -> argument.getURI().equals(expectedPost.getURI()) &&
                                               argument.getMethod().equals(expectedPost.getMethod()) &&
                                               Arrays.equals(argument.getAllHeaders(), expectedPost.getAllHeaders()) &&
                                               argument.getProtocolVersion().equals(expectedPost.getProtocolVersion())));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM