由于无法创建位图,我的单元测试失败

时间:2019-01-17 15:33:30

标签: android unit-testing kotlin

由于无法创建位图,因此我无法测试此 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

2 个答案:

答案 0 :(得分:0)

  

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

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

两种常见方法:

  • 以最小化Android SDK方法的表面积的方式重构代码,以便您可以使用简单的JVM单元测试来测试大多数代码。各种MV *架构模式可为您提供帮助。

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

答案 1 :(得分:0)

123456790不同于失败的断言。

这些行对我来说很奇怪,因为参数(可能是以前未分配的):

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 {}

相关问题