【问题标题】:why the method of spy can not be stubbed?为什么spy的方法不能被stub?
【发布时间】:2019-04-18 18:15:46
【问题描述】:

我想知道 Mockito 创建的间谍是否可以被存根以返回一个值。在下面的代码中,spy.get(0) 被存根返回一个字符串“不可访问”。所以我认为 assertEquals() 应该通过。但是测试方法最终会抛出一个 IndexOutOfBoundsException 异常。所以,我认为必须调用 get() 的真实版本而不是存根版本。 spy可以被stub吗?

@Test
public void doReturnUsage() throws Exception {
    List<String> list = new ArrayList<String>();
    List<String> spy = spy(list);
    when(spy.get(0)).thenReturn("not reachable");
    assertEquals("not reachable", spy.get(0));
}

【问题讨论】:

标签: mockito stub spy


【解决方案1】:

当您使用@Spy 时,语法与使用普通注入实例时略有不同。

Mockito.doReturn("not reachable").when(spy).get(0);

当您想“模拟”您正在测试的类下的公共方法时,Spy 很有用。 例如

Class A {
  public void methodA() {
    // do something
  }
  public void methodB() {
    // do something 
    call methodA();
   // do something else 
  }
}

这里,类A的公共方法“methodA”是从公共方法“methodB”中调用的。因此,在为“methodB”编写测试用例时,我们使用 spy 模拟对“methodA”的调用。并且我们独立测试“methodA”

【讨论】:

  • 感谢您的回复。但我不知道为什么我们应该使用 doReturn() 而不是 thenReturn()。 IMO, doReturn() 用于存根 void 方法。 get() 方法根本不是 void 方法。
  • 当你使用spy时,这是我们需要遵循的语法。即doReturn vs thenReturn。 doNothing() 用于 stub void 方法。
  • 如何决定何时使用 doReturn,何时使用 thenReturn?
  • size() 可以被存根:when(spy.size()).thenReturn(100);
  • 存根get(0)会抛出异常:when(spy.get(0)).thenReturn("good");
【解决方案2】:

考虑另一个例子:

@Test
public void thenReturnUsage() {
    List<String> list = new LinkedList<String>();
    List<String> spy = spy(list);
    // doReturn(100).when(spy).size(); 
    when(spy.size()).thenReturn(100);
    int size = spy.size();
    assertEquals(100, size);
}

这个测试又通过了。但是 spy.size() 是用 when().thenReturn() 而不是 doReturn().when() 存根的。为什么?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多