【问题标题】:How to unit test a class that uses context?如何对使用上下文的类进行单元测试?
【发布时间】:2020-09-30 09:13:19
【问题描述】:

我正在尝试测试一个简单的方法。

我有这门课:

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() 方法进行单元测试,但我不知道该怎么做,我应该使用工具测试并通过上下文还是可以使用类似 mockk 的东西?

我可以用 mockk 做到这一点吗?

@Test
fun cloudVelocity() { 
    val cloud: Cloud = mockk()                
    //update cloud velocity
    //assert that the velocity changed 
}

【问题讨论】:

    标签: android unit-testing kotlin mockk


    【解决方案1】:

    在这种情况下很难对你的类进行单元测试,因为它不仅取决于上下文,还取决于BitmapBitmapFactoryCanvas

    如果您将业务和绘图逻辑分开在不同的类中,也许会更好。例如,您的 Cloud 对象将仅包含纯业务逻辑,您可以轻松对其进行测试。另一方面,您可以创建CloudDrawer 类,该类将包含Canvas/Context/Bitmap 的绘图逻辑

    在大多数更简单的情况下,您可以使用特殊接口替换Context。例如,我们在课堂上使用getString()。但是我们想测试这些类。在这种情况下,我们在Context 上使用这个抽象:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2012-01-08
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2011-01-15
      相关资源
      最近更新 更多