我正在用Junit写一个ParametrizedTest。该测试的论据来自于一个枚举源。
我希望用该枚举构造一个对象,并使模拟的方法返回该对象。
然而,当我尝试这样做时,我得到(我认为是)一个不相关的错误消息。
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
以下是代码:
public static enum CodeEnum {
S1("S1"),
S2("S2)
}
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@Mocked
MockedObject mockedObject;
@InjectMocks
Foo underTest
@ParameterizedTest
@EnumSource(CodeEnum.class)
public void test_ParametrizedTest(CodeEnum enum) {
Output expectedReturn = Output.builder().code(enum).build();
// Given
when(mockedObject.method(any()))
.thenReturn(expectedReturn);
// when
val result = underTest.method();
// then
assertEquas(enum, result.getCode())
}
}
我怀疑输入不应该是any()
,所以我创建了一个为测试提供数据的方法,并使用了@MethodSource注释。
该方法将输入的参数返回给模拟,并从模拟返回expectedReturn。
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@Mocked
MockedObject mockedObject;
@InjectMocks
Foo underTest
@ParameterizedTest
@MethodSource("dataProvider")
public void test_ParametrizedTest(MockedInput mockedInput, Output expectedReturn) {
Output expectedReturn = Output.builder().code(enum).build();
// Given
when(mockedObject.method(mockedInput))
.thenReturn(expectedReturn);
// when
val result = underTest.method();
// then
assertEquas(enum, result.getCode())
}
private static Stream<Arguments> dataProvider() {
return Stream.of(
Arguments.of(mockedInput1, Output.builder().code(CodeEnum.S1).build()),
Arguments.of(mockedInput2, Output.builder().code(CodeEnum.S2).build())
)
}
}
如何使模拟对象从参数化测试返回参数?
发布于 2022-10-31 20:51:58
我所用的跑步者是不正确的。我将其更改为使用MockitoExtension,测试运行良好。
@ExtendWith(MockitoExtension.class)
public class FooTest {
@Mocked
MockedObject mockedObject;
@InjectMocks
Foo underTest
@ParameterizedTest
@MethodSource("dataProvider")
public void test_ParametrizedTest(MockedInput mockedInput, Output expectedReturn) {
Output expectedReturn = Output.builder().code(enum).build();
// Given
when(mockedObject.method(mockedInput))
.thenReturn(expectedReturn);
// when
val result = underTest.method();
// then
assertEquas(enum, result.getCode())
}
private static Stream<Arguments> dataProvider() {
return Stream.of(
Arguments.of(mockedInput1, Output.builder().code(CodeEnum.S1).build()),
Arguments.of(mockedInput2, Output.builder().code(CodeEnum.S2).build())
)
}
https://stackoverflow.com/questions/74230080
复制