【问题标题】:Order of evaluation of Hamcrest CombinableMatcherHamcrest CombinableMatcher 的评估顺序
【发布时间】:2021-08-23 16:05:52
【问题描述】:

我想为 matcher_1 AND matcher_2 OR matcher_3 and matcher_4 这样的匹配器编写逻辑,其中 matcher_i 只是 hamcrest 匹配器的占位符。

我决定像这样使用CombinableMatcher 编写它-

new CombinableMatcher<String>(matcher_1).and(matcher_2).or(matcher_3).and(matcher_4)

现在,问题是匹配器的评估顺序是什么?

((((matcher_1) AND matcher_2) OR matcher_3) and matcher_4) 还是 像((matcher_1 AND matcher_2) OR (matcher_3 and matcher_4)) 这样的任何其他订单?

【问题讨论】:

    标签: java mockito hamcrest


    【解决方案1】:

    Matcher 结果将从左到右进行评估。因此,它将是 ((((matcher_1) AND matcher_2) OR matcher_3) and matcher_4) 而不是 ((matcher_1 AND matcher_2) OR (matcher_3 and matcher_4))

    以下示例在 mockito 3.11 和 hamcrest 2.2 中运行证明了上述情况 -

        @RunWith(MockitoJUnitRunner.class)
        public class SomeTest {
        
            @Mock
            SomeInterface mock;
        
        
            @Test
            public void test(){
        
                when(mock.complicatedMethod(eq(1), MockitoHamcrest.argThat(
        
                        new CombinableMatcher<String>(equalTo("hello"))
                                .and(containsString("ello"))
                                .or(CoreMatchers.<String>instanceOf(String.class))
                                .and(containsString("XYZ"))
        
        
                ) )).thenReturn("done");
        
                System.out.println(mock.complicatedMethod(1 ,"hello"));// Prints null
        
            }
        
        
        
        }
    
    interface SomeInterface {
    
        public String complicatedMethod(int i , String str) ;
    }
    

    如果匹配器结果按此顺序评估 ((matcher_1 AND matcher_2) OR (matcher_3 and matcher_4)) [顺便说一下,布尔运算符的 Java 优先顺序],则“完成”将被打印,但它失败并打印 null,这意味着 ((((matcher_1) AND matcher_2) OR matcher_3) and matcher_4) 是它正在考虑什么。

    【讨论】:

      【解决方案2】:

      很高兴看到有人理解编写匹配器的想法。

      我想知道您为什么关心匹配器的顺序?理想情况下,这无关紧要,因为您也不知道匹配器被调用的频率。

      如果您在这个细节级别上遇到问题,最好编写一个自定义匹配器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-05
        • 2012-02-22
        相关资源
        最近更新 更多