我如何使用 Mockito 进行模拟?

How do I mocking with Mockito?

我正在进行单元测试,我无法对 Mockito 进行编程以覆盖部分代码
如何让 Mockito return 我得到一些有效的东西?当我得到 spec 时,我得到一个 IllegalArgumentExpection 那个代码。不好意思问的比较白痴,最近才开始写测试

我的测试

@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.");
        }
    }

覆盖率

您在此处使用的 BasicDBObject 实例

BasicDBObject spec = specDBDAO.findLastOne(new BasicDBObject("_id", new ObjectId(idSpec)));

与您在此处使用的 BasicDBObject 实例不同

when(dao.findLastOne(new BasicDBObject("_id", "erro"))).thenReturn(new BasicDBObject());

解决方案

1 在 BasicDBObject 上覆盖 equals()hashCode(),因此相等性基于 iderrno 以及任何其他值是必要的。

2 在设置期望时使用org.mockito.Matchers class给你匹配器,例如

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