例如:
struct foo
在类似情况下,我有一个void方法。如何测试这种无效方法?
答案 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
}
}