Bitmap.CreateBitmap 在 JUnit 测试 Android Studio 中返回 null

Mat*_*tto 3 java junit android bitmap createbitmap

我需要创建一个假位图图像来测试(JUnit 测试)我的个人添加和获取自定义 LinkedList 的方法,但 Bitmap.createBitmap 返回错误:

java.lang.RuntimeException:未模拟 android.graphics.Bitmap 中的方法 createBitmap。

这是我的 JUnitTest 的代码:

public class TicketsIteratorTest {

    Bitmap img_Bmp;
    TicketsIterator<Bitmap> TicketsList = new TicketsIterator();

    /*
     * Test for the add e get methods, check if the element just insert it's the same of the one just extract.
     */
    @Test
    public void Add_n_Get() throws Exception {
        int i = 0, numIMG = 100;
        Bitmap[] IMG_Generated;
        IMG_Generated = new Bitmap[numIMG];

        // Generate numIMG of imagine to insert into the Iterator and it save each one of it into an
        // Bitmap array usefull for testing of the get method
        while (i <= numIMG) {
            // Generation of the fake Ticket Bitmap
            try {
                img_Bmp = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

                IMG_Generated[i] = img_Bmp;

            } catch (Exception e) {
                // Print the cause of the error just generated
                e.getCause().printStackTrace();
            }

            // Addition of the imagine just created
            TicketsList.add(img_Bmp);

            i++;
        }

        // Test if the imagine inserted it is correct
        while (i <= numIMG) {
            assertTrue(IMG_Generated[i] == TicketsList.get(IMG_Generated[i]));
            i++;
        }
    }
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助。

Dar*_*cki 5

您是在常规单元测试中还是在 Android 测试中使用它?如果您从正常的单元测试中调用它,android 类将被替换为空/空实现。这意味着对 Bitmap.createBitmap() 的调用将始终返回 null,甚至不检查您的参数等。

过去我在 Bitmap 和 Base64OutputStream 上遇到过类似的问题。一切似乎都工作得很好,除了后面没有发生任何事情 ;) 每当您看到类似的行为时,请检查类是否来自 Android 框架 - 这很可能是问题的原因。

我希望就是这样,我可以帮助你。在我的例子中,我正在使用 PowerMock 并且只是模拟 Bitmap 类来返回 Bitmap 模拟实例。

此致,

达里乌什·维切基


ana*_*ish 5

Instrumentation Testcase 在这种情况下会起作用,Unit testcase 将为位图返回 null(失败),因为它与 Android 框架有关。

我在从连接的设备(移动)文件路径读取文件时遇到类似类型的问题Unit test,以防它无法读取,但可以在Instrumentation Test