在Account类中,我有一个要测试的方法public Account reserveA()
,在reserveA
内称为方法public Bank DAO.createB()
。有没有办法在测试方法中调用reserveA()
但忽略调用DAO.createB()
?这些方法都不是无效的。
我尝试过:
doNothing().when(Account).reserveA(param1, param2);
但这不是正确的方法。
答案 0 :(得分:2)
doNothing()仅保留用于void方法。 如果您的方法返回了某些内容,则您也必须这样做(否则抛出异常)。 如果您在其他地方使用了结果,那么根据Account.reserveString()的复杂程度,您可能需要模拟的不仅仅是此一个方法调用。
尝试在非无效方法上使用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());
}
}
为其创建Test类的
@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