英文:
Mockito multiple ObjectMapper values
问题
我在模拟mapper.convertValue
函数,使其能够返回同一类的两种不同返回类型。
Target target1 = new Target();
target1.setId("123");
Target target2 = new Target();
target2.setId("345");
Mockito.when(mapper.convertValue(anyMap(), eq(Target.class)))
.thenReturn(target1)
.thenReturn(target2);
实际调用代码如下,我希望在这里模拟objectmapper
,根据键值对返回target1
或target2
。当前情况是按照我定义的顺序覆盖了一个方法。
List<Pair<String, Target>> targetPairs = targetPairList.entrySet().stream()
.map(pair -> ImmutablePair.of(pair.getKey(), mapper.convertValue(pair.getValue().getSourceAsMap(), Target.class)))
.collect(Collectors.toList());
非常感谢您的帮助。
英文:
im mocking mapper.convertValue to return 2 different return type of same class.
Target target1 = new Target();
target1.setId("123);
Target target2 = new Target();
target2.setId("345);
Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).thenReturn(target1);
Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).thenReturn(target2);
The actual code is called this way , where i want to mock the objectmapper to return target1 or target2 depending on the pair. Right now its overriding one over the other in order i have defined.
List<Pair<String, Target>> targetPairs = targetPairList.entrySet().stream()
.map(pair -> ImmutablePair.of(pair.getKey(), mapper.convertValue(pair.getValue().getSourceAsMap(), Target.class)))
.collect(Collectors.toList());
Any help is appreciated.
答案1
得分: 1
你可以尝试类似这样的代码。
Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).then(invocationOnMock -> {
if (invocationOnMock.getArguments()[0] == givenObjectOne) {
return target1;
} else if (invocationOnMock.getArguments()[0] == givenObjectTwo) {
return target2;
}
return null;
});
关于 Mockito 中的 Answer 的更多细节可以在这里找到:https://javadoc.io/static/org.mockito/mockito-core/3.5.2/org/mockito/stubbing/Answer.html
英文:
You can try something like this.
Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).then(invocationOnMock -> {
if (invocationOnMock.getArguments()[0] == givenObjectOne) {
return target1;
} else if (invocationOnMock.getArguments()[0] == givenObjectTwo) {
return target2;
}
return null;
});
More details about Answer from Mockito can be found here. https://javadoc.io/static/org.mockito/mockito-core/3.5.2/org/mockito/stubbing/Answer.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论