Reputation: 2247
I'm doing unit testing and I can't program the Mockito to cover a portion of the code.
How do I get Mockito return me something valid? I get an IllegalArgumentExpection
that code when i get spec
. Sorry if it's an ignorant question, I started writing tests recently.
My test
@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"));
}
My code
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.");
}
}
Coverage
Upvotes: 2
Views: 117
Reputation: 8202
The BasicDBObject
instance you're using here
BasicDBObject spec = specDBDAO.findLastOne(new BasicDBObject("_id", new ObjectId(idSpec)));
is different to the BasicDBObject
instance you're using here
when(dao.findLastOne(new BasicDBObject("_id", "erro"))).thenReturn(new BasicDBObject());
Solution
1 Override equals()
and hashCode()
on BasicDBObject
so equality is based on, for example, id
and errno
along with any other values that are necessary.
2 Use the org.mockito.Matchers class to give you a matcher when you set up the expectation, for example
when(dao.findLastOne(Matchers.any(BasicDBObject.class).thenReturn(new BasicDBObject());
// any BasicDBObject instance will trigger the expectation
or
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
You can find more information on this here.
Upvotes: 2