【发布时间】:2021-08-06 22:23:23
【问题描述】:
我有一个更新方法,但我在进行单元测试时遇到了问题。在该方法中,我需要验证要更改的对象是否存在于数据库中,并且我还需要检查用户插入的新数据是否会导致记录重复。为此,我在两个不同的时间使用findById() 在数据库中进行搜索:
public void update(Form form, Long storeCode, Long productCode, Long purchaseQuantity) {
var id = new PrimaryKeyBuilder(DiscountPK.builder().build()).build(storeCode,productCode, purchaseQuantity);
var targetToUpdate = repository.findById(id).orElseThrow(NotFoundException::new);
var dataToInsert = SerializationUtils.clone(id);
dataToInsert.setPurchaseQuantity(form.getPurchaseQuantity());
var newPk = repository.findById(dataToInsert);
throwExceptionIf(newPk.isPresent(), new DuplicatedPkException());
targetToUpdate.getId().setPurchaseQuantity(form.getPurchaseQuantity());
targetToUpdate.setDiscountPercentage(form.getDiscountPercentage());
repository.save(targetToUpdate);
}
问题是:我无法在单元测试中区分这两个findById() 指令。不是成功通过它,而是在我的第一次验证中抛出NotFoundException。就好像第一个 given() 语句被忽略,只考虑第二个语句
@Test
public void update_successfully() {
var targetToUpdate = ObjectFactory.createMain();
var form = FormFactory.createUpdateForm();
var id = ObjectFactory.createFirstAux();
var dataToInsert = ObjectFactory.createSecondAux();
given(repository.findById(id)).willReturn(Optional.of(targetToUpdate));
given(repository.findById(dataToInsert)).willReturn(Optional.empty());
given(repository.save(any())).willReturn(targetToUpdate);
service.update(form, STORE_CODE, PRODUCT_CODE, PURCHASE_QUANTITY);
verify(repository).save(targetToUpdate);
}
奖励代码:构建传入findById()的对象的类
public class PrimaryKeyBuilder {
private final DiscountPK id;
public PrimaryKeyBuilder(DiscountPK id) {
this.id = id;
}
public DiscountPK build(Long storeCode, Long productCode, Long purchaseQuantity) {
id.setPurchaseBoxQuantity(purchaseBoxQuantity);
id.setProduct(Product.builder().id(ProductPK
.builder().productCode(productCode).store(Store.builder().code(storeCode).build()).build()).build());
return id;
}
}
【问题讨论】:
-
当您更改
acceleratorRepository.findById(id)部分以匹配任何参数时是否返回Optional.of(accelerator)?我怀疑匹配器不认为这个id对象与您在update函数中传递的任何内容相同。 -
你好。术语“加速器”是在此处转录代码的错误。我调整了。关于您的假设,我还认为在我的测试中传递的 id 可能被认为与 Service 类执行的不同,即使值相同但对象本身不同(在服务中,id 是用新的)
-
DiscountPK类是否定义了equals和hashCode方法? -
你好,@蒂姆·摩尔。 DiscountPK中没有equals/hashcode
-
要让 Mockito 检测到两个不同的实例匹配,您需要定义
equals和hashCode。
标签: java junit java-8 mockito java-11