Mocking a class: (This will mock the whole class and all the methods in it.)
A aMock = Mockito.mock(A.class);
Mockito.when(aMock.method()).thenReturn(5l);
To mock-a-single-method-in-java use Mockito Spy
A a = new A(); ( where Class A has two method - method1() and method2() )
A aSpy = Mockito.spy(a);
Mockito.when(aSpy.method1()).thenReturn(5l);
call to aSpy.method2() will be actual method call to method2 without any mock effect.
Refer : how-to-mock-a-single-method-in-java
NOTE: When you are mocking a class make sure you use/inject the mock version only.
Mockito provide simple way to pass parameter to a mocked class method:
e.g : aSpy.method(anyInt(), anyString())
this is mock for -> a.method(int i, String stg)
MOCKITO LIMITATION:
Mockito has a few limitations worth remembering. They are generally technical restrictions, but Mockito authors believe using hacks to work around them would encourage people to write poorly testable code. Mockito cannot:
- mock final classes
- mock enums
- mock final methods
- mock static methods
- mock private methods
- mock hashCode() and equals()
No comments:
Post a Comment