Powermock不会为java.time.ZonedDateTime创建模拟

编程入门 行业动态 更新时间:2024-10-11 05:20:51
本文介绍了Powermock不会为java.time.ZonedDateTime创建模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图使用PowerMockito为java.time.ZonedDateTime创建模拟,并且我期待ZonedDateTime的模拟对象。而是创建了实际的对象,因此无法模拟ZonedDateTime类的方法。

I tried to create mock for java.time.ZonedDateTime using PowerMockito and I was expecting the mock object for ZonedDateTime. Instead, actual object is getting created and hence I cannot mock the methods of ZonedDateTime class.

以下是我的代码段

import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; @RunWith(PowerMockRunner.class) @PrepareForTest({ZonedDateTime.class}) public class ZonedDateTimeTest { @Test public void test(){ ZonedDateTime attribute = mock(ZonedDateTime.class); when(attribute.format(any(DateTimeFormatter.class))).thenReturn("dummy"); //test code here } }

为此,当我尝试打印使用以下行创建的对象 System.out.println(attribute.toString());

In addition to this, when I try to print the object created using following line System.out.println(attribute.toString());

我收到以下异常:

java.lang.NullPointerException 在java.time.ZonedDateTime .toString(ZonedDateTime.java:2208)在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)在sun .reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)在org.powermock.core.MockGateway.doMethodCall(MockGateway.java:124)在org.powermock.core.MockGateway.methodCall(MockGateway .java:185)

有人可以帮我解决这个问题吗?我应该创建GitHub问题吗?

Can someone please help me to workaround this? Should I create a GitHub issue?

推荐答案

在您的类中创建一个方法,例如

Create a method in your class like

public class SomeClass{ public static void main(String[] args) { LocalDateTime now = getCurrentLocalDateTime(); System.out.println(now); } private LocalDateTime getCurrentLocalDateTime() { return LocalDateTime.now(); }

}

然后在测试类中使用

@PrepareForTest(SomeClass.class) @RunWith(PowerMockRunner.class)

在TestCase中

LocalDateTime tommorow= LocalDateTime.now().plusDays(1); SomeClass classUnderTest = PowerMockito.spy(new SomeClass()); PowerMockito.when(classUnderTest, "getCurrentLocalDateTime").thenReturn(tommorow);

更多推荐

Powermock不会为java.time.ZonedDateTime创建模拟

本文发布于:2023-11-25 06:40:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628709.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:会为   Powermock   java   ZonedDateTime   time

发布评论

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

>www.elefans.com

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