Mockito for beginners

Mockito for beginners:

Mockito is an open source testing framework, and it is a widely used for junit testing with mocking beans/repositories in frameworks such as spring mvc & spring boot. The framework allows the creation of test double objects in automated unit tests for the purpose of test-driven development or behavior-driven development. The framework’s name and logo are a play on mojitos, a type of drink.

How to Mock void method ?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
doNothing().when(couponRepository).deleteAll(Mockito.any());
doNothing().when(couponRepository).deleteAll(Mockito.any());
doNothing().when(couponRepository).deleteAll(Mockito.any());

Note: deleteAll is a void method.

How to Mock public methods of a same class ?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
NgDeveloper ngDeveloperSpy = Mockito.spy(new NgDeveloper());
when(ngDeveloperSpy.getAuthor()).thenReturn("Mirthbees");
NgDeveloper ngDeveloperSpy = Mockito.spy(new NgDeveloper()); when(ngDeveloperSpy.getAuthor()).thenReturn("Mirthbees");
NgDeveloper ngDeveloperSpy = Mockito.spy(new NgDeveloper());
when(ngDeveloperSpy.getAuthor()).thenReturn("Mirthbees");

Note: getAuthor() is the public method which we need to mock, so we have created a spy of a class then called getAuthor() method and mocked the response as “Mirthbees” using when and thenReturn.

How to test Controller & Service classes using PowerMock with Mockito ?

How to Mock Map in Mockito / PowerMock ?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
when(couponServiceImpl.getCoupons(Mockito.anyMap())).thenReturn(couponsList);
// couponsList - is the list constructed in the mock creator of your class.
// here couponSerivceImpl is mocked like this,
@Mock
CouponServiceImpl couponServiceImpl;
when(couponServiceImpl.getCoupons(Mockito.anyMap())).thenReturn(couponsList); // couponsList - is the list constructed in the mock creator of your class. // here couponSerivceImpl is mocked like this, @Mock CouponServiceImpl couponServiceImpl;
when(couponServiceImpl.getCoupons(Mockito.anyMap())).thenReturn(couponsList);

// couponsList - is the list constructed in the mock creator of your class.

// here couponSerivceImpl is mocked like this,
@Mock
CouponServiceImpl couponServiceImpl;

How to Mock List in Mockito / PowerMock ?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
when(couponServiceImpl.getCoupons(Mockito.anyList())).thenReturn("MyString");
// couponServiceImpl should be mocked at the top of the class like this.
@Mock
CouponServiceImpl couponServiceImpl;
when(couponServiceImpl.getCoupons(Mockito.anyList())).thenReturn("MyString"); // couponServiceImpl should be mocked at the top of the class like this. @Mock CouponServiceImpl couponServiceImpl;
when(couponServiceImpl.getCoupons(Mockito.anyList())).thenReturn("MyString");

// couponServiceImpl should be mocked at the top of the class like this.
@Mock
CouponServiceImpl couponServiceImpl;

How to return the mocked classes in cases like caching / any spring config testing / any BPMN testing scenario’s ?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
MyCacheOrBPMNClassToReturn myCacheOrBPMNClassToReturn = Mockito.mock(MyCacheOrBPMNClassToReturn.class);
when(couponServiceImpl.getCacheOrBPMNStuffs()).thenReturn(myCacheOrBPMNClassToReturn);
// here too couponServiceImpl should be mocked like this at the top of the class
@Mock
CouponServiceImpl couponServiceImpl;
MyCacheOrBPMNClassToReturn myCacheOrBPMNClassToReturn = Mockito.mock(MyCacheOrBPMNClassToReturn.class); when(couponServiceImpl.getCacheOrBPMNStuffs()).thenReturn(myCacheOrBPMNClassToReturn); // here too couponServiceImpl should be mocked like this at the top of the class @Mock CouponServiceImpl couponServiceImpl;
MyCacheOrBPMNClassToReturn myCacheOrBPMNClassToReturn = Mockito.mock(MyCacheOrBPMNClassToReturn.class);
when(couponServiceImpl.getCacheOrBPMNStuffs()).thenReturn(myCacheOrBPMNClassToReturn);

// here too couponServiceImpl should be mocked like this at the top of the class
@Mock
CouponServiceImpl couponServiceImpl;

What is the recommended way to use Mockito ?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Mockito.doReturn(myListOrMapOrWhateverNeededToReturn).when(couponServiceImpl).getCoupons(Mockito.anyList());
// You can mock the couponServiceImpl either with @Mock at the top of the class or using Mockito.mock.
CouponServiceImpl couponServiceImpl = Mockito.mock(CouponServiceImpl.class);
(or)
@Mock
CouponServiceImpl couponServiceImpl;
Mockito.doReturn(myListOrMapOrWhateverNeededToReturn).when(couponServiceImpl).getCoupons(Mockito.anyList()); // You can mock the couponServiceImpl either with @Mock at the top of the class or using Mockito.mock. CouponServiceImpl couponServiceImpl = Mockito.mock(CouponServiceImpl.class); (or) @Mock CouponServiceImpl couponServiceImpl;
Mockito.doReturn(myListOrMapOrWhateverNeededToReturn).when(couponServiceImpl).getCoupons(Mockito.anyList());

// You can mock the couponServiceImpl either with @Mock at the top of the class or using Mockito.mock.
CouponServiceImpl couponServiceImpl = Mockito.mock(CouponServiceImpl.class);

(or)
@Mock
CouponServiceImpl couponServiceImpl;

What and all can not be mocked in Mockito ?

  • We can not mock/stub/verify the final, private, equals() and hashcode() methods.
  • We also won’t be able to mock and test any methods present inside the non-public classes.

How to enrich some value inside void method in Mockito ?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
doAnswer( invocationOnMock -> {
Coupon coupon = (Coupon) invocationOnMock.getArguments()[0]; // coupon is 0th argument so setting as 0
coupon.setStatus("published");
return null;
}).when(mockCouponHelperUtility).enrichCoupon(any (Coupon.class), Mockito.any());
doAnswer( invocationOnMock -> { Coupon coupon = (Coupon) invocationOnMock.getArguments()[0]; // coupon is 0th argument so setting as 0 coupon.setStatus("published"); return null; }).when(mockCouponHelperUtility).enrichCoupon(any (Coupon.class), Mockito.any());
doAnswer( invocationOnMock -> {
Coupon coupon = (Coupon) invocationOnMock.getArguments()[0]; // coupon is 0th argument so setting as 0 
coupon.setStatus("published");
return null;
}).when(mockCouponHelperUtility).enrichCoupon(any (Coupon.class), Mockito.any());

How to read property/xml files from src/test/resources folder in your junit test?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@SpringBootTest
public class XmlPropertyRead{
@Test
public void testXmlAttribute() throws Exception {
Path relPath = Paths.get("src", "test", "resources", "my_sample_xml.xml");
String content = null;
try {
content =Files.lines(relPath).collect(Collectors.joining(System.lineSeparator()));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
assertTrue(true);
}
}
@SpringBootTest public class XmlPropertyRead{ @Test public void testXmlAttribute() throws Exception { Path relPath = Paths.get("src", "test", "resources", "my_sample_xml.xml"); String content = null; try { content =Files.lines(relPath).collect(Collectors.joining(System.lineSeparator())); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } assertTrue(true); } }
@SpringBootTest
public class XmlPropertyRead{
    @Test
    public void testXmlAttribute() throws Exception {
        Path relPath = Paths.get("src", "test", "resources", "my_sample_xml.xml");
        String content = null;
        try {
            content =Files.lines(relPath).collect(Collectors.joining(System.lineSeparator()));
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertTrue(true);
    }
}

Leave a Reply