【问题标题】:my unit test fails due to Bitmap can not be created由于无法创建位图,我的单元测试失败
【发布时间】:2019-06-11 20:21:06
【问题描述】:

我无法测试这个 getGeneratedBitmap 函数,因为无法创建位图。

import android.graphics.Bitmap

class BitmapGenerator(query: String, private val width: Int, private val height: Int) {

    private var sizeExpansion: SizeExpansion = SizeExpansion(query, width, height)

    private var bitmap: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

    private var expandedQuery: String

    private var colors: IntArray

    private var colorsLength: Int = 0

    init {
        colorsLength = sizeExpansion.getExpectedLength()
        expandedQuery = sizeExpansion.getExpandedString()
        colors = IntArray(colorsLength)
        generateColorArray()
    }

    private fun generateColorArray(): IntArray {
        for (x in 0 until colorsLength) {
            colors[x] = ColorGenerator().generateColorAccToChar(expandedQuery[x])
        }
        return colors
    }

    fun getGeneratedBitmap(): Bitmap {
        bitmap.setPixels(colors, 0, width, 0, 0, width, height)
        return bitmap
    }
}

我尝试测试的方式是:

import org.junit.Test

import org.junit.Assert.*

class BitmapGeneratorTest {

@Test
fun getGeneratedBitmap() {
    assertNotEquals(BitmapGenerator("salih",25,25).getGeneratedBitmap(),null)
}
}

当我运行这个测试时,它在Bitmap.createBitmap 上抛出异常

java.lang.IllegalStateException: Bitmap.createBitmap(widt… Bitmap.Config.ARGB_8888) must not be null

【问题讨论】:

  • 抛出的异常是什么?不要说它没有发布完整的堆栈跟踪就抛出了异常。
  • JVM单元测试还是androidTest?
  • 它在 (/src/test/java/)

标签: android unit-testing kotlin


【解决方案1】:

它位于 (/src/test/java/)

这些是 JVM 单元测试,无需任何 Android 运行时即可运行。通常 JVM 单元测试以 Android 平台方法返回默认值的方式进行配置。 null 是返回引用类型的方法的默认值,例如 Bitmap.createBitmap()。尝试将此 null 分配给 Kotlin 非 null 类型会导致运行时异常。

两种常见的方法:

  • 重构您的代码,使 Android SDK 方法的表面积最小化,这样您就可以使用普通的 JVM 单元测试来测试您的大部分代码。各种 MV* 架构模式对此有所帮助。

  • 在 Android 运行时使用 Android 依赖项运行测试,即将其设为 androidTest。

【讨论】:

    【解决方案2】:

    IllegalStateException 与失败的断言完全不同。

    这些行对我来说看起来很奇怪,因为参数(可能)以前没有分配:

    private var sizeExpansion: SizeExpansion = SizeExpansion(query, width, height)
    private var bitmap: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    

    我可以看到private val width: Int, private val height: Int ...但仍然想知道。

    首先定义var bitmap: Bitmap 并在init {} 上分配值(正如名称可能暗示的那样)。

    ...并将测试移至src/androidTest

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-16
      • 2013-02-26
      • 1970-01-01
      • 2017-02-16
      • 2012-12-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      相关资源
      最近更新 更多