使用 Mockito 验证空行失败时

When using Mockito verify failing on empty row

尝试用以下测试来测试我的客户:

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);
    }

在生产代码中是这样的:

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

结果是在同一个执行和实际中出现“比较失败”,有一个空行。 看起来像这样: 预计:

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

实际:

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

编辑:如评论中所述,大多数 Apache HTTP 客户端 API 类 不会覆盖 java.lang.Object#equals,因此您不能 可靠地 使用org.mockito.ArgumentMatchers#eq(T)。 您将要使用 org.mockito.ArgumentMatchers#argThat 匹配器,在谓词中定义相等条件。

我是这样测试的:

import static org.mockito.ArgumentMatchers.argThat;

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

    // Given
    HttpClient client = mock(HttpClient.class);
    URI        uri    = URI.create("
    HttpPost   post   = new HttpPost(uri);

    // When
    client.execute(post);

    // Then
    URI      expectedUri  = URI.create("
    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())));
  }