java - JUnit 测试方法无法返回值

为什么 JUnit 测试方法不能返回值?

Documentation说(强调我的):

Test methods and lifecycle methods may be declared locally within the current test class, inherited from superclasses, or inherited from interfaces (see Test Interfaces and Default Methods). In addition, test methods and lifecycle methods must not be abstract and must not return a value.

为什么要这样强制执行

这纯粹是一种设计选择吗?这是最佳做法吗?

最佳答案

我还没有看到提到的一件事是,这个设计决定背后的原因之一是历史原因。

在用注解标记的测试用例之前,它们由 JUnit 通过反射分析 - 所有 public void 方法,其名称以 test 开头,但没有t 有任何参数,被认为是框架运行的测试用例。

如果这些方法也允许返回一个值,您就不会创建一个以 test 开头的公共(public)辅助方法来计算某些测试中常用的值,否则框架运行器会尝试运行它。

我想无论如何你都应该将它们设为私有(private)。

此外,这也是“以动词开头的方法名称应该某事”(而不是计算某事)的高峰期。

https://stackoverflow.com/questions/60654124/

相关文章:

python - 如何在 asyncio create_task 中更新全局变量

swift - 将核心数据同步到 CloudKit 公共(public)数据库

javascript - 使用 JavaScript 检测按键持续时间

python - 从包含文本格式数据的其他列创建 Pandas 数据框的列

kubernetes - 为什么 k8s pod 在 ConfigMap 中找不到 key?

session - Nuxt Apollo 具有用于基于 session 的身份验证的动态 head

javascript - YouTube 视频 API 片段标题包含 Next.js 中的特殊字符

firebase - 在 Firebase 云存储中加载预览时出错

haskell - 函数重载以最小化重复模式

javascript - 使用javascript在数组中首先缺少正整数?