4

我需要创建一个假的位图图像来测试(JUnit 测试)我个人的自定义 LinkedList 的 add 和 get 方法,但 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++;
        }
    }

感谢您的帮助。

4

2 回答 2

6

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

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

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

此致,

达里乌什·维切奇

于 2018-02-14T13:25:36.500 回答
3

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

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

于 2018-03-22T13:55:07.650 回答