Mockito
Mockito
Mockito
2
Mockito
It is built on the top of JUnit Tool.
It is given to perform unit testing by mocking the Local Dependent or
external Dependent objects.
• Let us assume DAO class coding is not completed, but we Service coding
is completed and we want finish unit testing of service class. Then we
need to create Mock object/ Fake object/ dummy object for DAO class
and assign/ inject to Service class, in order write test cases on service
class methods.
Note: Mock objects are for temporary needs, mostly they will be used in the
Unit Testing. These mock objects created in test methods or Test case class
does not real code.
Note: While working with Spy object will be having real object also.
3
Instead of creating classes manually to prepare Mock, Stub and Spy
objects, we can use mocking frameworks available in the market which
are capable generate such classes dynamically at runtime as lnMemory
classes (That classes that are generated in the JVM memory of RAM).
4
|-> LoginMgmtServiceImpl.java (c)
com.nt.dao
|-> LoginDAO.java
• Develop the above directory Structure and package, class, XML file and
add the jar dependencies in pom.xml file then use the following code
with in their respective file.
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-
jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-
jupiter-engine -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope> 5
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-
core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.6.28</version>
<scope>test</scope>
</dependency>
</dependencies>
ILoginDAO.java
package com.nt.dao;
public interface ILoginDAO {
public int authenticate(String username, String password);
}
ILoginMgmtService.java
package com.nt.service;
public interface ILoginMgmtService {
public boolean login(String username, String password);
}
LoginMgmtServiceImpl.java
package com.nt.service;
import com.nt.dao.ILoginDAO;
public class LoginMgmtServiceImpl implements ILoginMgmtService {
private ILoginDAO loginDAO;
public LoginMgmtServiceImpl(ILoginDAO loginDAO) {
this.loginDAO = loginDAO;
}
@Override
public boolean login(String username, String password) {
if (username.equals("")||password.equals(""))
throw new IllegalArgumentException("Empty
credentials"); 6
//use DAO
int count =loginDAO.authenticate(username, password);
throw new IllegalArgumentException("Empty
credentials");
//use DAO
int count =loginDAO.authenticate(username, password);
if (count==0)
return false;
else
return true;
}
}
TestLoginMgmtService.java
package com.nt.test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import com.nt.dao.ILoginDAO;
import com.nt.service.ILoginMgmtService;
import com.nt.service.LoginMgmtServiceImpl;
public class TestLoginMgmtService {
private static ILoginMgmtService loginSevice;
private static ILoginDAO loginDAOMock;
@BeforeAll
public static void setupOnce() {
/* Create Mock/ Fake/ Dummy Object
* mock(-) generates lnMemory class implementing
* ILoginDAO(l) having null method definitions for
*authenticate(-,-) method */
loginDAOMock = Mockito.mock(ILoginDAO.class);
// Create Service class object
loginSevice = new LoginMgmtServiceImpl(loginDAOMock);
}
@AfterAll 7
public static void clearOnce() {
loginDAOMock = null;
loginSevice = null;
@AfterAll
public static void clearOnce() {
loginDAOMock = null;
loginSevice = null;
}
//Test Methods
@Test
public void testLoginWithValidCredentials() {
// Provide stub (Temporary functionality) for DAO's
authenticate method
Mockito.when(loginDAOMock.authenticate("raja",
"rani")).thenReturn(1);
assertTrue(loginSevice.login("raja", "rani"));
}
@Test
public void testLoginWithInvalidCredentials() {
// Provide stub (Temporary functionality) for DAO's
authenticate method
Mockito.when(loginDAOMock.authenticate("raja",
"rani1")).thenReturn(0);
assertFalse(loginSevice.login("raja", "rani1"));
}
@Test
public void testLoginWithNoCredentials() {
assertThrows(IllegalArgumentException.class, ()->{
loginSevice.login("", "");
});
}
}
8
TestMockVsSpy.java
package com.nt.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class TestMockVsSpy {
@Test
public void testList() {
List<String> listMock = Mockito.mock(ArrayList.class);
List<String> listSpy = Mockito.spy(new ArrayList());
listMock.add("table");
listSpy.add("table");
System.out.println(listMock.size()+" "+listSpy.size());
}
}
Note: Spy objects are useful to check how many time methods are called
whether they are called or not. Because Spy object is always linked with real
object (for this use Mockito.verify(-,-) method).
ILoginDAO.java
public int addUser(String username, String role);
ILoginMgmtService.java
public String registerUser(String username, String role);
LoginMgmtServiceImpl.java
@Override
public String registerUser(String username, String role) {
if
(!role.equalsIgnoreCase("")&&!role.equalsIgnoreCase("visitor")) {
loginDAO.addUser(username, role);
return "User Added";
}
else {
return "User Not Added";
}
}
10
TestLoginMgmtService.java
@Test
public void testRegisterWithSpy() {
//spy object
ILoginDAO loginDAOSpy = Mockito.spy(ILoginDAO.class);
ILoginMgmtService loginService = new
LoginMgmtServiceImpl(loginDAOSpy);
loginService.registerUser("raja", "admin");
loginService.registerUser("suresh", "visitor");
loginService.registerUser("jani", "");
Mockito.verify(loginDAOSpy, Mockito.times(1)).addUser("raja",
"admin");
Mockito.verify(loginDAOSpy,
Mockito.times(0)).addUser("suresh", "visitor");
Mockito.verify(loginDAOSpy, Mockito.never()).addUser("jani",
"");
}
Mockito Annotations:
▪ @Mock: To generate mock object
▪ @Spy: To generate spy object
▪ @lnjectMocks: To Inject Mock or Spy Objects Service class.
MockitoAnnotations.openMocks(this); - call this method in @Before or
constructor Testcase class in order to activate Mockito Annotations.
ILoginMgmtService.java
@InjectMocks
private LoginMgmtServiceImpl loginSevice;
@Mock
private static ILoginDAO loginDAOMock;
public AnnoTestLoginMgmtService() {
MockitoAnnotations.openMocks(this);
}
11
Note: To write stub functionality according agile user stories/ JIRA user stories
(given, when, then)
BDDMockito.given(loginDAOMock.authenticate("raja", "rani")).willReturn(1);
Mockito.when(loginDAOMock.authenticate("raja", "rani")).thenReturn(1);
12