Powermock不会为java.time.ZonedDateTime创建模拟 [英] Powermock does not create mock for java.time.ZonedDateTime

查看:203
本文介绍了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创建模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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