【问题标题】:Mockito: set value to spy object but get nullMockito:将值设置为间谍对象但获得空值
【发布时间】:2022-10-17 04:08:09
【问题描述】:

我有一个测试用例,我想查看在执行期间是否正确设置了属性:

ContainerRequestContext requestContext = spy(ContainerRequestContext.class);
someMethodThatSetsTheSecurityContext(requestContext);

verify(requestContext).setSecurityContext(argument.capture());
assertEquals("myUserName", argument.getValue().getUserPrincipal().getName());
assertNotNull(requestContext.getSecurityContext());

现在,如果我运行它,verify() 和 assertEquals() 方法返回 true,但由于某种原因 requestContext.getSecurityContext() 为空。 我知道对于模拟对象没有真正的实现,但我认为间谍对象应该在这种情况下工作。

【问题讨论】:

  • 为什么需要间谍?您不能简单地断言requestContext.getSecurityContext().getUserPrincipal().getName() 等于“myUserName”吗?为什么要通过间谍跳过篮球?
  • 我还需要存根 ContainerRequestContext 的一些方法,这就是我使用 spy 对象的原因。

标签: java junit mockito


【解决方案1】:

尝试改用 Mockito.argThat 并查看它是否会改变它:

verify(requestContext).setSecurityContext(Mockito.argThat(x -> x.getValue().getUserPrincipal().getName().equals("myUserName"))); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2016-03-16
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多