模拟对象使用Mockito调用final类静态方法

编程入门 行业动态 更新时间:2024-10-28 02:22:18
本文介绍了模拟对象使用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类静态方法

本文发布于:2023-10-31 07:05:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545377.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   对象   方法   final   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!