Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何对使用上下文的类进行单元测试?_Android_Unit Testing_Kotlin_Mockk - Fatal编程技术网

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")