Showing posts with label mockito. Show all posts
Showing posts with label mockito. Show all posts

Monday, October 11, 2021

@Mock,@InjectMocks and @RunWith(MockitoJunitRunner.class) in mockito

 In previous example we have created a Mock like below-

DataService dataServiceMock = mock(DataService.class);

but we can create mock using @Mock annotations.

@Mock

DataService dataServiceMock;

when mock is created then we need to inject into beans 

@InjectMocks

SomeBusinessImpl businessImpl;// dataServiceMock will inject into SomeBusinessImpl

Then we no need to inject this dependencies through constructor or setter injection.

MockitoJUnitRunner checks if all settings are ok or any mistakes have take places.

so put it to the top of the test class

@RunWith(MockitoJUnitRunner.class)


Friday, October 1, 2021

Previous example using mockito

 package com.example.mockitoEx.MockitoEx;

import static org.junit.jupiter.api.Assertions.assertEquals;

import static org.mockito.Mockito.mock;

import static org.mockito.Mockito.when;


import org.junit.jupiter.api.Test;


class SomeBusinessTestMock {

@Test

public void findGreatestFromAllData() {

DataService dataServiceMock = mock(DataService.class);

when(dataServiceMock.retrieveAllData()).thenReturn(new int[] { 24, 15, 10 });


SomeBusinessImpl businessImpl = new SomeBusinessImpl(dataServiceMock);


int result = businessImpl.findTheGreatestFromAllData();

assertEquals(24, result);

}

}

Using mock method we can create a mock object of any interface or object.


Tuesday, September 28, 2021

Why to use mockito?

 Suppose we have a class which have a dependency which will provide some data and based on those data we will do some work,

public class SomeBusinessImpl {

private DataService dataService;//dependency

public SomeBusinessImpl(DataService dataService) {

super();

this.dataService = dataService;

}

int[] data = dataService.retrieveAllData();

int greatest = Integer.MIN_VALUE;

int findTheGreatestFromAllData() {

for (int value : data) {

if (value > greatest) {

greatest = value;

}

}

return greatest;

}

}

interface DataService {

int[] retrieveAllData();

}

Test class:

class SomeBusinessTest {

@Test

public void findGreatestFromAllData() {

SomeBusinessImpl someBusiness = new SomeBusinessImpl(new DataServiceStub());

int result = someBusiness.findTheGreatestFromAllData();

assertEquals(24, result);

}

}

class DataServiceStub implements DataService {//Implementation of DataService

@Override

public int[] retrieveAllData() {

return new int[] { 24, 10, 12 };

}

}

What to do if the logic inside DataServiceStub changed. Every time we will need to give different implementation of the DataService . But if we can create mock using mockito . By using mockito we can easily create dummy data .


Testing controller

------Controller------------- @RestController @RequestMapping("/items") public class ItemController {     private final ItemServic...