Mockito多个ObjectMapper值

huangapple go评论141阅读模式
英文:

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,根据键值对返回target1target2。当前情况是按照我定义的顺序覆盖了一个方法。

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(&quot;123);

Target target2 = new Target();
target2.setId(&quot;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&lt;Pair&lt;String, Target&gt;&gt; targetPairs = targetPairList.entrySet().stream()
                .map(pair -&gt; 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 -&gt; {
  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

huangapple
  • 本文由 发表于 2020年8月19日 11:17:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63479497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定