Mockito使用静态类和方法返回void

时间:2016-07-08 16:21:21

标签: java junit mockito powermockito

我正在尝试在调用方法时使用Mockito更改方法的实现,但我同时有两个问题1)我的类是静态的,2)我的方法返回void。

PowerMockito.doAnswer(new Answer<Void>() {
        public Void answer(InvocationOnMock invocation) throws IOException {
            DeliveryQueue.publishToQueue(testQueue, "message");
            return null;
        }
    }).when(DeliveryQueue).publishToQueue(DeliveryQueue.REAL_QUEUE, "message");

正如您所看到的,我试图告诉我的测试,当我们向REAL_QUEUE发布消息时,我们应该将其发送到testQueueREAL_QUEUEstatic final因此无法直接更改(我尝试过反映但没有成功)。目前的问题是when(DeliveryQueue)无法正常工作,因为即使我上面使用了PowerMockito.mockstatic(DeliveryQueue.class),它仍然需要一个模拟对象。我也试过了when(DeliveryQueue.getInstance()),但它也没有被标记为被模拟的对象。

1 个答案:

答案 0 :(得分:1)

您是否在班级添加了@PrepareForTest(DeliveryQueue.class)

试试这个:.when(DeliveryQueue.class); DeliveryQueue.publishToQueue(DeliveryQueue.REAL_QUEUE, "message");