gpt4 book ai didi

java - 业务方法中的错误检查,也就是进行防御性编程

转载 作者:行者123 更新时间:2023-11-29 05:01:10 24 4
gpt4 key购买 nike

我开始向大型 Java 代码库添加测试。我经常在我正在测试的 session bean 中看到以下内容:

public OrderDTO getOrderDTO(Long id) {
Order o = (Order)entityManager.find(Order.class, id);
OrderDTO dto = new OrderDTO(o.getId(), o.getCurrency());
return dto;
}

编写单元测试来破坏此代码(发送 null 或不存在的 ID)非常容易。当我这样做时,一半的团队开发人员说:

We are not error checking everything. If you parameter is rubbish you will know fast!

另一半说:

We must add ifs to the id and then to the o and if any of them are null the null is what we return.

单元测试的目的不就是准确地找到这些问题吗?(是的,我是在征求意见!)

是的,从 Long 切换到 long 会删除一个 if。

最佳答案

虽然这在某种程度上是基于意见的,但很少有人会说如果将 null 作为参数返回 null 是正确的。如果我要添加任何东西,它最多是一个 IllegalArgumentException(或者甚至是 NPE),当 null 被传入时。

可以创建一个测试来检查该方法是否以一致的方式失败,但它实际上是在测试 JPA 提供程序的行为,而不是您的代码。

关于java - 业务方法中的错误检查,也就是进行防御性编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32050001/

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