Mock objects calling final classes static methods with Mockito

19,716

Solution 1

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

Solution 2

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.

Share:
19,716
user962206
Author by

user962206

Updated on June 18, 2022

Comments

  • user962206
    user962206 almost 2 years

    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 there a way around this?

    e.g.

    when(mockObject.someMethod(FinalClass.staticMethod(someParam)).anotherMethodCall)
        .thenReturn("someString");
    
  • anergy
    anergy almost 11 years
    doesn't matter, Mockito cant mock Final classes
  • user962206
    user962206 almost 11 years
    so you mean it is mocking a final class? I thought it is just calling the static method of a final class
  • niaomingjian
    niaomingjian almost 7 years
    What if my class has annotated with @RunWith(Theories.class)?