android - 由于无法创建位图,我的单元测试失败
问题描述
我无法测试这个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
解决方案
它位于 (/src/test/java/)
这些是在没有任何 Android 运行时的情况下运行的 JVM 单元测试。通常 JVM 单元测试以 Android 平台方法返回默认值的方式进行配置。Anull
是返回引用类型的方法的默认值,例如Bitmap.createBitmap()
. 尝试将此 null 分配给 Kotlin 非 null 类型会导致运行时异常。
两种常见的方法:
以最小化 Android SDK 方法的表面区域的方式重构您的代码,以便您可以使用普通的 JVM 单元测试来测试您的大部分代码。各种 MV* 架构模式对此有所帮助。
在 Android 运行时使用 Android 依赖项运行您的测试,即使其成为 androidTest。
推荐阅读
- python - 给定一个列表字典,是否有一种 Python 的智能方法来比较每个列表的第 i 个元素并提取最大值?
- google-tasks - Due Date is not updating on google
- matplotlib - 使用 keras load_img 函数时,matplotlib as plt 不起作用
- python-3.x - 基于相同行和其他行标记 Pandas 行
- python-3.x - 可视化递归的扩展和收缩过程
- linux - 如何构建 netcore 3.0 Webapi 并部署到 Azure Linux 应用服务
- mongodb - 在 Intellij 或 MongoDB Compass 中添加 sslAllowInvalidHostnames 选项
- java - 如何为双 ArrayList 实现 Parcelable?
- elasticsearch - 带有 wait_for_completion 的 Elasticsearch updateByQuery
- android - 从 Google Fit API 读取准确的睡眠数据