gpt4 book ai didi

java - 我如何使用 Mockito 进行模拟?

转载 作者:行者123 更新时间:2023-11-30 08:51:59 25 4
gpt4 key购买 nike

我正在进行单元测试,我无法对 Mockito 进行编程以覆盖部分代码
如何让 Mockito 返回有效的东西?当我得到 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.");
}
}

覆盖范围 enter image description here

最佳答案

您在此处使用的 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 类为您提供匹配器

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 的更多信息.

关于java - 我如何使用 Mockito 进行模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30349380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com