使用 Mockito 调用最终类静态方法的模拟对象 [英] Mock objects calling final classes static methods with Mockito

查看:37
本文介绍了使用 Mockito 调用最终类静态方法的模拟对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始模拟我们应用程序的不同层.我的一个模拟对象在调用最终类静态方法时返回 NPE.有没有办法解决这个问题?

I just started mocking different layers of our application. I came to a point where one of my mock objects is returning NPE when it calls a final class static method. Is there a way around this?

例如

when(mockObject.someMethod(FinalClass.staticMethod(someParam)).anotherMethodCall)
    .thenReturn("someString");

推荐答案

你必须同时使用 PowerMock 和 Mockito.

You have to use PowerMock and Mockito together.

我不明白您的代码片段要做什么,但以下代码片段允许 Calendar 类的静态 getInstance() 方法返回模拟日历 对象.也许这会给你指明正确的方向

I don't understand what your code snippet is trying to do, but the following snippets allow the static getInstance() method of the Calendar class to return a mocked Calendar Object. Maybe that'll point you in the right direction

在班级层面:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Calendar.class)
public class XXXXXX {

在您的测试方法中:

PowerMockito.mockStatic(Calendar.class);
    Calendar calendar = mock(Calendar.class);
    when(calendar.get(eq(Calendar.HOUR_OF_DAY))).thenReturn(3);

    Mockito.when(Calendar.getInstance()).thenReturn(calendar);

这篇关于使用 Mockito 调用最终类静态方法的模拟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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