Mockito when()... then()NullPointerException [英] Mockito when()...then() NullPointerException

查看:350
本文介绍了Mockito when()... then()NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

productsInDatabse是一个hashMap,输出是枚举,scanCode来自经过测试的类

productsInDatabse is a hashMap, output is enum, scanCode is from class which is tested

   public static boolean isInDataBase(int code) {
        return productsInDatabse.containsKey(code);
    }

我已经进行了测试:

@Test
public void testScanCodeForCodeNotFound() {

    Database db = Mockito.mock(Database.class);
    when(db.isInDataBase(444)).thenReturn(false);
    output = scanner.scanCode("444");
    assertTrue(output == ProductProcessing.PRODUCT_NOT_FOUND);

}

但是when()... then()随NPE返回.我在调用时看到的例子完全是这样的.所以我的问题是错误在哪里,因为我认为when()... then()就像那样工作.

But when()...then() returns with NPE. I saw examples when invoking was exactly like this. So my question is where is the bug, because I thought when()...then() works likes that.

Stacktrace:

Stacktrace:

Testcase: testScanCodeForCodeNotFound(iodevices.BarCodesScannerTest):   Caused an ERROR
null
java.lang.NullPointerException
    at database.Database.isInDataBase(Database.java:66)
    at iodevices.BarCodesScannerTest.testScanCodeForCodeNotFound(BarCodesScannerTest.java:50)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)


Test iodevices.BarCodesScannerTest FAILED

推荐答案

isInDataBase()声明中删除static.

如果无法删除静态,请参见以下内容:用Mockito模拟静态方法

See this if you can't remove the static: Mocking static methods with Mockito

这篇关于Mockito when()... then()NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆