Android 如何对使用上下文的类进行单元测试?
我正在尝试测试一种简单的方法 我有这门课:Android 如何对使用上下文的类进行单元测试?,android,unit-testing,kotlin,mockk,Android,Unit Testing,Kotlin,Mockk,我正在尝试测试一种简单的方法 我有这门课: class Cloud @Inject constructor(var posx: Double = 0.0, var posy: Double = 0.0, var velocity: Double = 1.0, val context: Context){ val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.raw.cloud) f
class Cloud @Inject constructor(var posx: Double = 0.0, var posy: Double = 0.0, var velocity:
Double = 1.0, val context: Context){
val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.raw.cloud)
fun updateVelocity(){
velocity += 5.0
}
fun draw(canvas: Canvas){
canvas.drawBitmap(image,posx.toFloat() - (image.width / 2),posy.toFloat(),null)
}
}
我想对updateVelocity()
方法进行单元测试,但我不知道该如何使用工具测试并通过上下文测试,还是可以使用类似mock的东西
我能和莫克一起做这个吗
@Test
fun cloudVelocity() {
val cloud: Cloud = mockk()
//update cloud velocity
//assert that the velocity changed
}
在这种情况下,很难对类进行单元测试,因为它不仅取决于上下文,还取决于
位图
、位图工厂
和画布
如果您在不同的类中分离业务和绘图逻辑,可能会更好。例如,您的Cloud
对象将只包含纯业务逻辑,您可以轻松地对其进行测试。另一方面,您可以创建CloudDrawer
类,该类将包含具有Canvas/Context/Bitmap
在大多数simper情况下,您可以使用特殊接口替换上下文。例如,我们在类中使用getString()
。但是我们想测试这些类。在本例中,我们在上下文中使用这个抽象:
interface ResourceManager {
fun getColor(@ColorRes resId: Int): Int
fun getDrawable(@DrawableRes resId: Int): Drawable?
fun getString(@StringRes resId: Int): String
fun getString(@StringRes resId: Int, vararg formatArgs: Any): String
fun getStringArray(@ArrayRes resId: Int): Array<String>
fun getQuantityString(@PluralsRes resId: Int, quantity: Int, formatArgs: Int): String
}
val resource = mock(ResourceManager::class.java)
`when`(resource.getString(any(Int::class.java))).thenReturn("text")