我正在尝试为 JUnit 中的 RabbitAdmin 类创建一个模拟对象。
@Mock RabbitAdmin rabbitAdmin; @InjectMocks MyOriginalClass classObj;
以上是我声明的内容
Mockito.when(rabbitAdmin.getQueueProperties("responseQueueName").get("QUEUE_MESSAGE_COUNT")).thenReturn(0);
在我的测试方法中执行上述行时,我得到一个 NullPointerException。
让我把你的模拟电话分解成碎片
Mockito.when(
rabbitAdmin.getQueueProperties("responseQueueName")
.get("QUEUE_MESSAGE_COUNT")
).thenReturn(0);
在中间部分,你有以下内容:
rabbitAdmin.getQueueProperties("responseQueueName")
rabbitAdmin
本身是一个模拟对象,这意味着每个方法都有默认行为返回null
。如果您没有为 rabbitAdmin.getQueueProperties(anyString())
或 rabbitAdmin.getQueueProperties("responseQueueName")
指定任何行为,则此调用将返回 null
.
然后你有下一部分:
rabbitAdmin.getQueueProperties("responseQueueName")
.get("QUEUE_MESSAGE_COUNT")
如果您没有指定任何行为,那么您将调用 partically
null.get("QUEUE_MESSAGE_COUNT")
这将使您获得 NullPointerException
.
为了避免这个空指针,你可以做一些事情
// creating a properties mock
// this could also be a normal constructor call
Properties properties = Mockito.mock(Properties.class);
// returning 0 when QUEUE_MESSAGE_COUNT is called
Mockito.when(properties).get("QUEUE_MESSAGE_COUNT").thenReturn(0);
// returning properties when responseQueueName is called
Mockito.when(rabbitAdmin.getQueueProperties("responseQueueName")).thenReturn(properties);