【问题标题】:Mockito varargs Invalid use of argument matchersMockito varargs 参数匹配器的无效使用
【发布时间】:2016-12-13 12:35:16
【问题描述】:

测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MockabstractionApplication.class)
public class SimpleTest {

    @SpyBean
    private SimpleService spySimpleService;

    @Before
    public void setup() {
        initMocks(this);
    }

    @Test //fails
    public void test() throws Exception {
        when(spySimpleService.test(1, Mockito.<String>anyVararg())).thenReturn("Mocked!");
    }

}

服务

@Service
public class SimpleService {

    public String test(int i, String... args) {
        return "test";
    }

}

测试失败并显示下一条消息:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 参数匹配器的使用无效!预计 2 个匹配器,1 个记录:

我必须使用 int 作为第一个参数和任意数量的可变参数。

【问题讨论】:

    标签: java mockito


    【解决方案1】:

    如果您对一个参数使用匹配器,则必须对所有参数使用它。

    when(spySimpleService.test(Mockito.eq(1), Mockito.<String>anyVararg())).thenReturn("Mocked!");
    

    【讨论】:

    • Mockito.eq(1) 解决问题。谢谢!我会在 7 分钟内接受你的回答。
    【解决方案2】:

    你不能同时使用匹配器和正确的参数

    spySimpleService.test(1, Mockito.&lt;String&gt;anyVararg())

    可以替换为

    spySimpleService.test(anyInt(), Mockito.&lt;String&gt;anyVararg())

    【讨论】:

      【解决方案3】:

      我认为您需要为两个参数使用参数匹配器,你不能在那里混合和匹配。

      试试

      @Test //fails
      public void test() throws Exception {
          when(spySimpleService.test(anyInt(), Mockito <String>anyVararg())).thenReturn("Mocked!");
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-20
        • 1970-01-01
        相关资源
        最近更新 更多