对于以下 Kotlin 类:
class ProductLogic(
private val product: Product?
) {
fun shouldShow(): Boolean {
if (product == null) {
return false
}
val version = product.version!!
if (!Utils.isAtLeastVersionX(version.major, version.minor)) {
return false
}
return true
}
}
我正在尝试在 Kotlin 中编写参数化测试:
@RunWith(ParameterizedRobolectricTestRunner::class)
@Config(constants = BuildConfig::class, sdk = [19], packageName = "com.example")
class ProductLogicTest(
private val product: Product?,
private val shouldShow: Boolean
) {
@Before
fun setUp() {
// doReturn(VERSION).`when`(product).version // (2) Raises a NotAMockException
}
@Test
fun shouldShow() {
assertThat(ProductLogic(product).shouldShow(), `is`(shouldShow))
}
companion object {
@JvmStatic
@Parameters(name = "{index}: {0} => {1}")
fun data(): Collection<Array<Any?>> {
val productMock = mock<Product>(Product::class.java)
doReturn(VERSION).`when`(productMock).version // (1) Is not applied
return asList(
arrayOf(productMock, false),
// ...
)
}
}
我想参数化Product#version
属性的值。当我(1)在data()
函数中修改它的值时,它在运行测试时不会应用。当我 (2) 尝试在@Before
aNotAMockException
中修改其值时:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();
请注意,该示例已简化 - 真实ProductLogic
类包含更多参数,这些参数可以纠正使用参数化测试。