【发布时间】:2023-04-02 14:00:01
【问题描述】:
有没有办法在 Android 的本地单元测试中使用 android.graphics.Matrix。当我尝试使用矩阵对象时,我收到错误消息:java.lang.RuntimeException: Method getValues in android.graphics.Matrix not mocked.
我怀疑由于 Matrix 类使用本机方法,这意味着该类不能用于本地单元测试。所以为了使用它,我必须使用例如 Mockito 创建一个模拟对象。这是一个创建模拟对象的示例,它总是返回单位矩阵。
/**
* Create Mockito graphic matrix, since the matrix methods are native and are not supported
* in local unit testing. We need to use Mockito to mock a matrix, that always return the
* identity matrix, when getValues() method is called. Identity matrix is the default matrix
* with no transformations applied to it.
*/
fun getMockMatrix(): Matrix {
val mockMatrix = mock(Matrix::class.java)
doAnswer { invocation ->
val v = (invocation.arguments[0] as FloatArray)
// always set values to match the identity matrix, when getValues() method is called
v[0] = 1f
v[4] = 1f
v[8] = 1f
null
}.`when`(mockMatrix).getValues(FloatArray(9))
val matrixValues = FloatArray(9)
mockMatrix.getValues(matrixValues)
// check if the mocked matrix matches the identity matrix
assertArrayEquals(
matrixValues, floatArrayOf(
1f, 0f, 0f,
0f, 1f, 0f,
0f, 0f, 1f
)
)
return mockMatrix
}
这在某些情况下效果很好,例如当我需要将其用作虚拟对象时,但当我需要对其或映射点进行实际转换时,无法使用模拟对象来实现它。
现在我使用Instrumented Test 进行了测试,因为它使用模拟器,这样它就可以访问集成在 Android 操作系统中的本地方法,但是这些类型的测试比本地单元测试要慢得多。我的问题是,是否有办法创建可以使用 Matrix 类的本地单元测试?
【问题讨论】:
标签: android unit-testing kotlin matrix