【问题标题】:Powermock does not create mock for java.time.ZonedDateTimePowermock 不会为 java.time.ZonedDateTime 创建模拟
【发布时间】:2016-04-28 07:29:08
【问题描述】:

我尝试使用 PowerMockito 为 java.time.ZonedDateTime 创建模拟,我期待 ZonedDateTime 的模拟对象。相反,正在创建实际对象,因此我无法模拟 ZonedDateTime 类的方法。

下面是我的代码sn-p

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());

我得到以下异常:

java.lang.NullPointerException at java.time.ZonedDateTime.toString(ZonedDateTime.java:2208) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:124) at org.powermock.core.MockGateway.methodCall(MockGateway.java:185)

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

【问题讨论】:

    标签: powermock


    【解决方案1】:

    java.time.ZonedDateTime 是最终的系统类,因此只能使用workaround 模拟它。解决方法要求将使用模拟系统类的类添加到@PrepareForTest。您可以在documentation 找到更多信息。

    但是,如果可以模拟系统类,我建议您以不需要模拟系统类的方式重构您的代码。因为,不建议模拟类which you don't own.。您可以使用有意义的方法创建一个 util 类。

    【讨论】:

    • 第二段很有用。在我的例子中,模拟我的方法调用 ZonedDateTime 有帮助。
    【解决方案2】:

    在你的类中创建一个方法,比如

    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)
    

    在测试用例中

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

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多