Mock objects calling final classes static methods with Mockito

前端 未结 2 1312
名媛妹妹
名媛妹妹 2020-12-10 22:58

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 th

相关标签:
2条回答
  • 2020-12-10 23:43

    Mockito doesn't support mocking a final class.Have a look at PowerMock.It allows you to mock static methods and classes. It can work with Mockito, documentation explains how to do that.

    0 讨论(0)
  • 2020-12-10 23:46

    You have to use PowerMock and Mockito together.

    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

    At the class level:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Calendar.class)
    public class XXXXXX {
    

    In your test method:

    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);
    
    0 讨论(0)
提交回复
热议问题