【问题标题】:When using Mockito verify failing on empty row使用 Mockito 验证空行失败时
【发布时间】:2020-10-06 09:09:58
【问题描述】:

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

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

【问题讨论】:

    标签: java unit-testing testing junit mockito


    【解决方案1】:

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

    这是我的测试方法:

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

    【讨论】:

    • 现在试了,空行还是失败
    • 您介意提供HttpPost 对象的完整限定名吗?这可能是由于 Object.equals 方法实现不佳所致。
    • 你的意思是org.apache.http.client.methods.HttpPost吗?
    • 这解释了这个问题。 Apache HTTP 客户端中的大多数对象不会覆盖默认的java.lang.Object#equals 方法,因此导致无法使用org.mockito.ArgumentMatchers#eq(T)。不幸的是,你会想要使用org.mockito.ArgumentMatchers#argThat。编辑我的答案以向您推荐解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2018-11-02
    • 2016-10-23
    相关资源
    最近更新 更多