2

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");
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user962206
  • 15,637
  • 61
  • 177
  • 270
  • Mockito cannot mock final methods in general; however, I doubt that even removing `final` will help here... – fge Jun 13 '13 at 09:30
  • It is not possible with mockito to mock final classes or statis method. Although, i think you can do that with power mock. Maybe you can have a look http://code.google.com/p/powermock/ – nikkatsa Jun 13 '13 at 09:32
  • Sorry, for the confusion, I have updated my code snippet. kindly check it out – user962206 Jun 13 '13 at 09:35

2 Answers2

10

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);
Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
DaveH
  • 7,187
  • 5
  • 32
  • 53
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.

anergy
  • 1,374
  • 2
  • 13
  • 29