我正在进行单元测试,我无法对Mockito进行编程以涵盖部分代码。
如何让Mockito给我一些有效的东西?当我得到IllegalArgumentExpection
时,我得到spec
该代码。对不起,如果这是一个无知的问题,我最近开始写测试。
我的测试
@Bean
public SpecDBDAO getSpecDBDAO() {
SpecDBDAO dao = Mockito.mock(SpecDBDAO.class);
when(dao.findLastOne(new BasicDBObject("_id", "erro"))).thenReturn(new BasicDBObject());
return dao;
}
@Test
public void testAddLinha_validId() throws Exception {
planilhaService.addLinha("123", new BasicDBObject("_id", "erro"));
}
我的代码
public Planilha addLinha(String id, BasicDBObject body) {
String idSpec = body.getString("_id", "");
Planilha planilha = specDBPlanilhasDAO.get(id);
if (planilha == null) {
throw new NotFoundException("Planilha não encontrada.");
}
try {
BasicDBObject spec = specDBDAO.findLastOne(new BasicDBObject("_id", new ObjectId(idSpec)));
if (spec.isEmpty()) {
throw new NotFoundException("Especificação não encontrada.");
}
planilha.addLinha(spec);
planilha = specDBPlanilhasDAO.update(planilha);
return planilha;
} catch (IllegalArgumentException e) {
throw new BadRequestException("Id inválido.");
}
}
覆盖范围
答案 0 :(得分:2)
您在此处使用的BasicDBObject
个实例
BasicDBObject spec = specDBDAO.findLastOne(new BasicDBObject("_id", new ObjectId(idSpec)));
与您在此处使用的BasicDBObject
实例不同
when(dao.findLastOne(new BasicDBObject("_id", "erro"))).thenReturn(new BasicDBObject());
<强>解决方案强>
1覆盖equals()
上的hashCode()
和BasicDBObject
,因此相等基于例如id
和errno
以及必要的任何其他值
2使用org.mockito.Matchers类在设置期望时为您提供匹配器,例如
when(dao.findLastOne(Matchers.any(BasicDBObject.class).thenReturn(new BasicDBObject());
// any BasicDBObject instance will trigger the expectation
或
when(dao.findLastOne(Matchers.eq(new BasicDBObject("_id", "erro")).thenReturn(new BasicDBObject());
// any BasicDBObject equal to the used here instance will trigger the expectation. Equality is given by your overridden equals method
您可以在here找到更多相关信息。