【问题标题】:mockito -using one of the values from list of values to compare in matchermockito - 使用值列表中的一个值在匹配器中进行比较
【发布时间】:2016-04-21 14:22:37
【问题描述】:

我的方法接口是

Boolean isAuthenticated(String User)

如果有任何用户从列表中传入函数,我想从值列表中进行比较,那么它应该返回 true。

when(authService.isAuthenticated(or(eq("amol84"),eq("arpan"),eq("juhi")))).thenReturn(true);

我正在使用附加参数匹配器“或”,但上面的代码不起作用。我该如何解决这个问题?

【问题讨论】:

    标签: junit mockito matcher


    【解决方案1】:

    or 没有三参数重载。 (See docs.) 如果您的代码编译,您可能导入了与org.mockito.AdditionalMatchers.or 不同的or 方法。

    or(or(eq("amol84"),eq("arpan")),eq("juhi")) 应该可以工作。

    您也可以尝试通过argThat Mockito matcher 访问的isOneOf Hamcrest matcher

    when(authService.isAuthenticated(argThat(isOneOf("amol84", "arpan", "juhi"))))
        .thenReturn(true);
    

    【讨论】:

      【解决方案2】:

      您可以定义单独的答案:

      when(authService.isAuthenticated(eq("amol84"))).thenReturn(true);
      when(authService.isAuthenticated(eq("arpan"))).thenReturn(true);
      when(authService.isAuthenticated(eq("juhi"))).thenReturn(true);
      

      【讨论】:

        【解决方案3】:

        如果您对拉入库不感兴趣,可以迭代所有要添加到模拟中的值:

        // some collection of values
        List<String> values = Arrays.asList("a", "b", "c");
        
        // iterate the values
        for (String value : values) {
          // mock each value individually
          when(authService.isAuthenticated(eq(value))).thenReturn(true)
        }
        

        【讨论】:

          【解决方案4】:

          对我来说这是可行的:

          public class MockitoTest {
          
              Mocked mocked = Mockito.mock(Mocked.class);
          
              @Test
              public void test() {
                  Mockito.when(mocked.doit(AdditionalMatchers.or(eq("1"), eq("2")))).thenReturn(true);
          
                  Assert.assertTrue(mocked.doit("1"));
                  Assert.assertTrue(mocked.doit("2"));
                  Assert.assertFalse(mocked.doit("3"));
              }
          }
          
          interface Mocked {
              boolean doit(String a);
          }
          

          检查您是否正确设置了 mockito,或者您是否使用与我相同的 Matchers。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-10-31
            • 2019-11-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多