0% found this document useful (0 votes)
108 views12 pages

Mockito

Mockito is a Java library used for unit testing that allows mocking of dependencies. It creates mock objects that implement interfaces of the dependencies and replace the real dependencies. This allows testing units in isolation without other dependencies like databases. Mockito provides mock, stub, and spy objects to mock dependencies. Mock objects have no implemented behavior, stub objects provide canned answers, and spy objects extend real objects while allowing some methods to be mocked.

Uploaded by

varam10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views12 pages

Mockito

Mockito is a Java library used for unit testing that allows mocking of dependencies. It creates mock objects that implement interfaces of the dependencies and replace the real dependencies. This allows testing units in isolation without other dependencies like databases. Mockito provides mock, stub, and spy objects to mock dependencies. Mock objects have no implemented behavior, stub objects provide canned answers, and spy objects extend real objects while allowing some methods to be mocked.

Uploaded by

varam10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1

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.

Service class ---------------------------> DAO class --------------> DB s/w


I->business methods |-> Persistence methods
(having business logic) (persistence logic)

• 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.

• When Sharekhan.com website is under development, we cannot take


subscription of BSE component because they charge money for that.
Generally, this subscription will take after hosting/ releasing the
Sharekhan.com till that we need to take one mock BSE component and
assign to Service class of Sharekhan.com to perform Unit Testing.

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.

We can do this Mocking in 3 ways:


a. Using Mock object/ Fake object (Provides Temporary object)
b. Using Stub object (Providing some Functionality for the methods of
mock object like specifying for certain inputs or certain output should
come)
c. Using Spy object (It is called Partial Mock object/ Half mock object that
means if you provide new functionality to method that will be used
otherwise real object functionality will be used).

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).

List of Mocking Frameworks:


o Mockito (popular)
o JMockito
o EasyMock
o PowerMock
And etc.

Example Application setup:


[Testing LoginMgmtService class without keeping LoginDAO class ready]

Step 1: Create maven standalone App


File -> Maven Project -> next -> select maven-archetype-quickstart ->
Groupld: nit
Artifactld: MockitoUniTesting-LoginApp
Default package: com.nt.service

Step 2: Do following operations in pom.xml file


change java version to 13
Add the following dependencies (jars)
o junit-jupiter-api.5.7.0.jar
o junit-jupiter-engine.5.7.0.jar
o mockito-core.3.6.28.jar

Step 3: Develop service interface, service class


com.nt.service
|-> ILoginMgmtService.java (I)

4
|-> LoginMgmtServiceImpl.java (c)
com.nt.dao
|-> LoginDAO.java

Step 4: Develop Mockito based Test classes and DAO interface


Step 5: Run Tests.

Directory Structure of JUnitTestProject01:

• 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).

Stubbing on Mock and Spy object:


TestMockVsSpy.java
@Test
public void testList() {
List<String> listMock = Mockito.mock(ArrayList.class);
//mock
List<String> listSpy = Mockito.spy(new ArrayList());//spy
listMock.add("table");
//stubbing on mock 9
Mockito.when(listMock.size()).thenReturn(10);
listSpy.add("table");
listMock.add("table");
//stubbing on mock
Mockito.when(listMock.size()).thenReturn(10);
listSpy.add("table");
//stubbing on spy
Mockito.when(listSpy.size()).thenReturn(10);
System.out.println(listMock.size()+" "+listSpy.size());
}

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

You might also like