如何模拟没有参数的void方法?

时间:2018-11-27 17:11:12

标签: junit mocking mockito

例如:

struct foo

在类似情况下,我有一个void方法。如何测试这种无效方法?

1 个答案:

答案 0 :(得分:0)

使用void方法,您应该在void方法中测试与其相关对象的交互。我认为没有参数的void方法很少有用(但是如果您有有效的用例,请将其添加到您的问题中)。我为您提供了一个方法简单的示例,该方法带有一个参数,但使用void作为返回类型:

public class A {

  private DatabaseService db;
  private PaymentService payment;

  // constructor

  public void doFoo() {
    if(n < 2) {
      db.updateDatabase();
    } else {
      payment.payBill();
    }
  }

}

与此相关的单元测试如下所示

@RunWith(MockitoJUnitRunner.class)
public class ATest {

   @Mock
   DatabaseService db;

   @Mock
   PaymentService payment;

   @Test
   public void testDoFooWithNGreaterTwo() {
     A cut = new A(db, payment); // cut -> class under test
     cut.doFoo(3);
     verify(payment).payBill(); // verify that payment was called
   }

   @Test
   public void testDoFooWithNLessThanTwo() {
     A cut = new A(db, payment); // cut -> class under test
     cut.doFoo(1);
     verify(db).updateDatabase(); // verify that db was called
   }

}