忽略Mockito中测试方法内部的not void方法



在类Account中,我有一个要测试的方法public Account reserveA(),在reserveA中称为方法public Bank DAO.createB()。有没有办法在测试方法中调用reserveA()而忽略调用DAO.createB()?这些方法中没有一种是无效的。我试过了:

doNothing().when(Account).reserveA(param1, param2);

但这不是正确的方式。

doNothing((只为void方法保留。如果你的方法返回了一些东西,那么你也需要这样做(或者抛出异常(。根据Account.reserveString()的复杂性,若结果在其他地方使用,则可能需要模拟的不仅仅是这一个方法调用。

尝试在非void方法上使用doNothing()导致错误:

org.mockito.exceptions.base.MockitoException: 
Only void methods can doNothing()!
Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called

考虑这样的类别:

@Component
public class BankDao {
public BankDao() {}
public void createVoid() {
System.out.println("sth - 1");
}
public String createString(){
return "sth - 2";
}
}
@Service
public class Account {
@Autowired
private final BankDao DAO;
public Account(BankDao dao) {
this.DAO = dao;
}
public void reserveVoid() {
System.out.println("before");
DAO.createVoid();
System.out.println("after");
}
public void reserveString() {
System.out.println(DAO.createString());
}
}

针对哪个测试类别:

@RunWith(MockitoJUnitRunner.class)
public class AccountTest {
@Mock
private BankDao bankDao;
@InjectMocks
private Account account;
@Test
public void reserveVoid_mockBankDaoAndDontUseRealMethod() {
doNothing().when(bankDao).createVoid();
account.reserveVoid();
}
@Test
public void reserveString_mockBankDaoAndDontUseRealMethod() {
when(bankDao.createString()).thenReturn("nothing");
account.reserveString();
}
}

运行这样的测试将产生:

nothing
before
after

如果您将@Mock更改为@Spy,并使用doNothing((和when((删除行,那么您将调用原始方法。结果是:

sth - 2
before
sth - 1
after

相关内容

最新更新