2

I tried to find but couldnt get what i was looking for. Is it possible to do something like following in mockito?

when(TestServiceUtil.getTestItem()).thenReturn(someItem);
varun
  • 684
  • 1
  • 11
  • 30
  • 2
    Mokito can't do that on it's own, but can if you use it with PowerMock. See if this helps : http://stackoverflow.com/questions/17083432/mockito-mock-objects-calling-final-classes-static-methods/17084152#17084152 – DaveH Aug 18 '14 at 10:34
  • You can also read this : http://stackoverflow.com/questions/4482315/why-does-mockito-not-mock-static-methods – m4rtin Aug 18 '14 at 10:36

1 Answers1

1

In your pom.xml, add the following dependencies:

<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.5.6</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.5.6</version> <scope>test</scope> </dependency>

above your test class: @RunWith(PowerMockRunner.class) public class YourClassName

[...] @Before public void beforeTest() throws SQLException { PowerMockito.mockStatic(TestServiceUtil.class);

Now you can use (as you had it): when(TestServiceUtil.getTestItem()).thenReturn(someItem);

Last words - don't overuse PowerMockito. Focus on clean, object oriented code.

Marcus Biel
  • 430
  • 4
  • 15