【问题标题】:Mockito Matching parameterized method with multiple interface具有多个接口的 Mockito Matching 参数化方法
【发布时间】:2017-06-29 06:27:26
【问题描述】:

您好,我为我的服务创建了一个不错的接口,它接受实现 2 个接口的对象,但现在我很难为这个接口创建匹配器。

有人知道如何为以下内容创建匹配器吗?

<T extends HasDocumentTags & HasResources> ResponseEntity<Void> setDocumentMetadata(T t);

只是 any() 在这里没有帮助,因为该方法已经重载了两次

ResponseEntity<Void> setDocumentMetadata(List<Document> attachments);
ResponseEntity<Void> setDocumentMetadata(ApproveDocumentsCommand<?> command);

现在我正在尝试模拟服务并定义答案

when(service.setDocumentMetadata( ??? ).thenReturn(anAnswer);

我只是无法为 any()、eq() 或任何可以工作的东西找出正确的匹配器。 还是我在尝试不可能的事情(在 java8 中)? 你能帮助我吗?

【问题讨论】:

    标签: mockito matcher


    【解决方案1】:

    对类型 Document 和 ApproveDocumentsCommand 使用 any:

    when(service.setDocumentMetadata(any(Document.class)).thenReturn(anAnswer1);
    when(service.setDocumentMetadata(any(ApproveDocumentsCommand.class)).thenReturn(anAnswer2);
    

    我这个 any(Document.class) 和 any(ApproveDocumentsCommand.class) 应该是足够的。

    你也可以使用 ArgumentMatcher ,如果你需要检查类型的参数和一些额外的检查:

        when(service.setDocumentMetadata(argThat(new MyCommonMatcher<>())))
             .thenReturn(responseEntityOk);
        when(service.setDocumentMetadata(argThat(new MyDocumentMatcher<>())))
            .thenReturn(responseEntityOk);
        when(service.setDocumentMetadata(argThat(new MyApproveDocumentsCommandMatcher<>()))) 
           .thenReturn(responseEntityOk);
    
    class MyCommonMatcher<T extends HasDocumentTags & HasResources> 
                                                          extends ArgumentMatcher<T>{
    
        @Override
        public boolean matches(Object argument) {
            return (argument instanceof HasResources) && (argument instanceof HasDocumentTags);
        }
    }
    
    class MyDocumentMatcher<T extends HasDocumentTags & HasResources> 
                                                           extends ArgumentMatcher<T>{
    
        @Override
        public boolean matches(Object argument) {
            return argument instanceof Document;
        }
    }
    
    class MyApproveDocumentsCommandMatcher<T extends HasDocumentTags & HasResources> 
                                                             extends ArgumentMatcher<T>{
    
        @Override
        public boolean matches(Object argument) {
            return argument instanceof ApproveDocumentsCommand;
        }
    }
    

    【讨论】:

    • 谢谢答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2023-03-05
    • 2016-08-17
    相关资源
    最近更新 更多