gpt4 book ai didi

java - Mockito 答案仅被调用一次

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:42 25 4
gpt4 key购买 nike

我试图以下面的方式模拟 spring 的 applicationContext.getBean(String, Class) 方法 -

when(applicationContext.getBean(Mockito.anyString(), Mockito.eq(SomeClass.class))).thenAnswer(
new Answer<SomeClass>() {
@Override
public SomeClass answer(InvocationOnMock invocation) throws Throwable {
// doing some stuff and returning the object of SomeClass
}
});

场景是,applicationContext.getBean 方法将被调用多次,每次都使用不同的字符串,但使用相同的类(SomeClass.class)。

我在这里遇到的问题是,第一次调用 getBean 方法时就会调用答案。每次后续调用 getBean 时,我都会遇到以下异常 -

******org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));******

知道吗,如果我遗漏了什么?

最佳答案

@Kshitij

我在之前的项目中也遇到过同样的问题。我在下面的文档中遇到了这个: http://static.javadoc.io/org.mockito/mockito-core/2.16.0/org/mockito/Mockito.html#resetting_mocks

第 17 节解释了如何使用 reset()

示例:假设我们有 EvenOddService,它可以查找数字是偶数还是奇数,那么使用 reset() 的测试用例将如下所示:

when(evenOddService.isEven(20)).thenReturn(true);
Assert.assertEquals(evenOddController.isEven(20), true);

//allows to reuse the mock
reset(evenOddService);
Assert.assertEquals(evenOddController.isEven(20), true);

希望这有帮助:)。

关于java - Mockito 答案仅被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49387433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com