本文介绍了模拟对象使用Mockito调用final类静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚开始模拟我们应用程序的不同层。当我调用最终类静态方法时,我的一个模拟对象返回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()方法返回一个模拟的Calendar对象。也许这会指向正确的方向
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调用final类静态方法
发布评论