我的单元测试由于无法创建位图而失败 [英] my unit test fails due to Bitmap can not be created
问题描述
由于无法创建位图,因此我无法测试此 getGeneratedBitmap 函数.
I can not test this getGeneratedBitmap function, since Bitmap can not be created.
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
When I run this test, it throws exception on Bitmap.createBitmap
java.lang.IllegalStateException: Bitmap.createBitmap(widt… Bitmap.Config.ARGB_8888) must not be null
推荐答案
它位于(/src/test/java/)
it is at (/src/test/java/)
这些是JVM单元测试,无需任何Android运行时即可运行.通常,JVM单元测试是以Android平台方法返回默认值的方式配置的. null
是返回引用类型(例如Bitmap.createBitmap()
)的方法的默认值.尝试将此null分配给Kotlin nonnull类型会导致运行时异常.
These are JVM unit tests that run without any Android runtime. Usually JVM unit tests are configured in a way where Android platform methods return default values. A null
is a default value for a method returning a reference type, such as Bitmap.createBitmap()
. Trying to assign this null to a Kotlin nonnull type causes the runtime exception.
两种常见方法:
-
以最小化Android SDK方法的表面积的方式重构代码,以便您可以使用简单的JVM单元测试来测试大多数代码.各种MV *架构模式可以为您提供帮助.
Refactor your code in a way that the surface area to Android SDK methods is minimized so you can test most of your code with plain JVM unit tests. Various MV* architectural patterns help there.
在Android运行时上使用Android依赖项运行测试,即使其成为androidTest.
Run your tests with Android dependencies on an Android runtime, i.e. make it an androidTest.
这篇关于我的单元测试由于无法创建位图而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!