提问者:小点点

验证在Mockito中调用的下游方法(通过私有void重载方法)


我很难弄清楚如何测试我的方法<code>foo(int length,String name)</code>是否被调用。

我的并发症:

  1. 有一个重载的 void 方法,而且它是私有的(我无法将其从私有中更改,尽管为此目的可以工作)
  2. 它有一个我可以尝试测试的私人方法下游的公共方法(Bar.bar()),但不确定如何使用 Mockito 正确测试它
  3. 我正在尝试测试超过 5 和低于 5 的客户长度,以确保它在结束时命中一次私有 foo 方法,如果它低于,则不会命中。无论哪种方式,它都会击中公共foo(客户)一次。
  4. 如果可能的话,宁愿不使用Powermockito来简化
public class Foo {

  public void foo(Customer customer) {
    if (customer.length() > 5) {
       foo(customer.length(), customer.name());
    } else {
      return
    }
  }
  
  //Private overloaded method 
  private void foo(int length, String name) {
    bar.bar();
  }
  
}


public class Bar {

  public Order bar(int length, String name) {
    barProcessing(...)
  }

  private Order barProcessing(...) {
    ...calling another Bar method
  }
  
}

到目前为止我所尝试的:

模仿Foo和Bar类,加上执行一系列< code>when()语句,然后执行...

    < li >验证(foo,times(1))。foo(any(customer . class));(作品) < li >验证(bar,乘以(1))。bar(any(Integer.class),any(string . class));(失败,返回0) < li>doCallRealMethod()。当(foo)。foo(any(customer . class));(作品) < li>foo.foo(客户);(作品) < Li > bddmockito . given(bar . bar(" 123 ",日期))。willReturn(订单);(失败) < li>BDDMockito.then(bar)。应该()。bar(any(Integer.class),any(string . class));(失败)

除了我的并发症,这里还真是难住了。我还是Mockito的新手,对任何新的建议都持开放态度。


共1个答案

匿名用户

  1. 一般来说,测试公共API的行为。私有方法是一个实现细节;通过调用公共方法间接测试它们。
  2. 你在嘲笑bar并确认它被foo(客户)在某个地方使用是正确的。你说你已经“尝试”嘲笑它,但不是你实际上是如何做到的。你的#2和#6通常应该工作;实际调试你的代码并检查bar.bar()是否真的被调用,以及你的模拟是否被注入到你的Foo中。

经过一些澄清,您似乎误解了何时在测试中使用模拟。您专门为未测试的项目使用模拟;如果您正在测试Foo但随后模拟它,则您没有测试实际行为!相反,模拟Bar并提供它,但您可以模拟真实的Bar(例如将其作为构造函数参数传递)。