Powermock does not create mock for java.time.ZonedDateTime

前端 未结 2 512
无人及你
无人及你 2020-12-12 05:51

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 he

相关标签:
2条回答
  • 2020-12-12 06:04

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

    }

    And in the Test Class you use

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

    In TestCase

    LocalDateTime tommorow= LocalDateTime.now().plusDays(1);
    
    SomeClass classUnderTest = PowerMockito.spy(new SomeClass());
    
    PowerMockito.when(classUnderTest, "getCurrentLocalDateTime").thenReturn(tommorow);
    
    0 讨论(0)
  • 2020-12-12 06:16

    The java.time.ZonedDateTime is a final system class, so it could mocked only by using workaround. And the workaround requires that the class which uses mocked system class is added to @PrepareForTest. More information you may find in documentation.

    But event if it possible to mock system classes, I'd like recommend you refactor your code in way that will not required mocking system classes. Because, it's not recommended to mock classes which you don't own.. You may create a util class with meaningful method.

    0 讨论(0)
提交回复
热议问题