android - 为什么在给定 List 时为参数化 JUnit 测试抛出 IllegalArgumentException>,但适用于列表>
问题描述
在调试参数化测试时,我意识到如果参数作为列表 ( List<List<Any>>
) 传递,测试将无法运行,但与数组列表 () 一起工作正常List<Array<Any>>
。
示例类:
import com.google.common.truth.Truth
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class TestWithList(val input: List<Int>, val output: Int) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): List<List<Any>> =
listOf(
listOf(
listOf(1, 4, 3, 2),
4
)
)
}
@Test
fun `empty test`() {
Truth.assertThat(true).isTrue()
}
}
投掷
IllegalArgumentException:参数数量错误
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class TestWithArray(val input: List<Int>, val output: Int) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): List<Array<Any>> =
listOf(
arrayOf(
listOf(1, 4, 3, 2),
4
)
)
}
@Test
fun `empty test`() {
assertThat(true).isTrue()
}
}
完美运行。
为什么传递List
错误数量的参数?
解决方案
我不熟悉使用 JUnit 进行参数化测试。但是,我确实找到了这个。如果您查看方法签名:
public static Collection<Object[]> data()
在 Kotlin 中,即:
fun data() : Collection<Array<Any>>
你会看到它是一个集合,包含一个对象数组。List
是 Collection,但 aList
不是Array
. 这是一个二维系统,其中第二维包含您要传递的参数,包括长度。
由于他们在文档中使用 Array,我建议您这样做。
最近,他们引入了单一参数。签名如下所示:
@Parameters
public static Iterable<? extends Object> data()
再一次,List 是一个 Iterable。但是,就您而言,这是您最终在没有数组的情况下调用的那个。
结果,您将一个参数传递给了一个有两个参数的构造函数,该构造函数引发了异常。你传递了一个 Iterable>,它不是Collection<Array<Any>>
. 这意味着您最终创建了一个适用于单个参数的系统。由于构造函数接受两个参数,因此您会遇到异常。您传递一个参数(列表),但您需要两个参数。
这就是为什么使用数组有效而列表无效的原因;如果您使用列表,则假定您有一个参数构造函数,而与数组一样,它需要多个。据我所知,JUnit 不支持 Lists 而不是 Arrays 用于多参数构造函数。
TL;DR:数组起作用而列表不起作用的原因是因为它认为列表是单参数构造函数的参数,而与数组一样,它可以是任意数量的参数。
推荐阅读
- c# - 为什么我的 asp:Checkbox 在检查时返回 false?
- android - 如何更改偏好类别中的标题文本颜色
- javascript - 如何在一个 onClick/onPress 方法上传递 2 个道具?
- python-3.7 - 我在python中使用带有winsound的gTTS,文件正在保存,但它使windows声音
- python - 在python中生成不同维度的元组
- powershell - 我的 powershell 脚本如何为 Azure DevOps 构建的时间轴屏幕做出贡献?
- reactjs - 使用 Jest 和 React-test-renderer 测试伪类
- node.js - 如何在使用 Typescript 的 Angular 7 项目中为 Node.js 使用 cassandra 驱动程序
- firebase - 在某些节点上启用 Firebase 持久性
- java - 从涉及字符串的主方法调用方法时出错