首页 > 解决方案 > 由于无法创建位图,我的单元测试失败

问题描述

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

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

标签: androidunit-testingkotlin

解决方案


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

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

两种常见的方法:

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

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


推荐阅读