Hello guys, if you are writing unit test in Java then you know how difficult it is to write especially if you are testing a class which is dependent upon other class like HttpClient and you cannot connect to actual server. At those time, a mocking library like Mockito comes to rescue. Given the increased focus on unit testing and code coverage, I have find myself using Mockito more and more along with JUnit in last a couple of years but I haven't written many articles on Mockito yet but that is chaging now. In this article, I am going to share 10 essential Mockito examples which I belive every Java programmer should know. But, before we get to the 10 best examples that will teach you everything there is to know about Mockito in Java, let me tell you a little bit more about what it really is.
Mockito is basically an open-source framework that allows you to easily create test doubles or mocks. A test double is actually just a generic term for a particular case where you replace the production object for testing.
Mockito allows you to work with a variety of test doubles like stubs, spies, and mocks. Stubs are actually just some objects with a set of predefined return values. Spies are also very similar to stubs. But they can also record the stats related to how they are executed.
Mockito is basically an open-source framework that allows you to easily create test doubles or mocks. A test double is actually just a generic term for a particular case where you replace the production object for testing.
Mockito allows you to work with a variety of test doubles like stubs, spies, and mocks. Stubs are actually just some objects with a set of predefined return values. Spies are also very similar to stubs. But they can also record the stats related to how they are executed.
Mocks are also objects with predefined return values to method executions. It also has recorded expectations of the executions.
10 Examples Of Mockito In Java
In this list, we have compiled 10 examples of Mockito in Java. Keep reading to find out more.
1. Setting Up Mockito In Maven
To add Mockito, you need to add the latest Mockito version by Maven. See the following example
pom.xml
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.6.1</version>
<scope>test</scope>
</dependency>
build.gradle
testCompile group: 'org.mockito', name: 'mockito-core', version: '4.6.1'
You
can also process Mockito annotations with the help of JUnit 5. But you
will need to use the MockExtension. See the following example:
@ExtendWith(MockitoExtension.class)
public class ApplicationTest {
//code
}
In case you are using the legacy JUnit 4,
@RunWith(MockitoJUnitRunner.class)
public class ApplicationTest {
//code
}
public class ApplicationTest {
@Rule public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
//code
}
2. Annotations Is Mockito
You
can annotate an object using the @Mock annotation. This will also make
the code more readable and neat. You can specify the mock object name
which will be useful in case there are errors or something. Check out
the following example:
package com.journaldev.mockito.mock;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class MockitoMockAnnotationExample {
@Mock
List<String> mockList;
@BeforeEach
public void setup() {
//if we don't call below, we will get NullPointerException
MockitoAnnotations.initMocks(this);
}
@SuppressWarnings("unchecked")
@Test
public void test() {
when(mockList.get(0)).thenReturn("JournalDev");
assertEquals("JournalDev", mockList.get(0));
}
}
3. Creating A Mock In Mockito
You
can use the Mockito class mock() method for creating a mock object of a
certain class or even a interface. It is also one of the easiest ways
to create a mock.
package com.journaldev.mockito.mock;
import java.util.List;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class MockitoMockMethodExample {
@SuppressWarnings("unchecked")
@Test
public void test() {
// using Mockito.mock() method
List<String> mockList = mock(List.class);
when(mockList.size()).thenReturn(5);
assertTrue(mockList.size()==5);
}
}
In this example, you can see that we are using JUnit 5 for writing test cases along with Mockito to mock the objects.
4. Using Mockito spy() For Partial Mocking
If
you are looking to mock only some specific behaviours, you can call the
real methods for behaviours that are unstubbed. You can then create a
spy object using the Mockito spy() method.
package com.journaldev.mockito.mock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class MockitoSpyMethodExample {
@Test
public void test() {
List<String> list = new ArrayList<>();
List<String> spyOnList = spy(list);
when(spyOnList.size()).thenReturn(10);
assertEquals(10, spyOnList.size());
//calling real methods since below methods are not stubbed
spyOnList.add("Pankaj");
spyOnList.add("Meghna");
assertEquals("Pankaj", spyOnList.get(0));
assertEquals("Meghna", spyOnList.get(1));
}
}
5. The @InjectMocks Annotation
You can see the following example to understand how you can inject a mocked object into another object.
package com.journaldev.mockito.mock;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class MockitoInjectMockAnnotationExample {
@Mock
List<String> mockList;
//@InjectMock creates an instance of the class and
//injects the mocks that are marked with the annotations @Mock into it.
@InjectMocks
Fruits mockFruits;
@BeforeEach
public void setup() {
//if we don't call below, we will get NullPointerException
MockitoAnnotations.initMocks(this);
}
@SuppressWarnings("unchecked")
@Test
public void test() {
when(mockList.get(0)).thenReturn("Apple");
when(mockList.size()).thenReturn(1);
assertEquals("Apple", mockList.get(0));
assertEquals(1, mockList.size());
//mockFruits names is using mockList, below asserts confirm it
assertEquals("Apple", mockFruits.getNames().get(0));
assertEquals(1, mockFruits.getNames().size());
mockList.add(1, "Mango");
//below will print null because mockList.get(1) is not stubbed
System.out.println(mockList.get(1));
}
}
class Fruits{
private List<String> names;
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
}
6. The @Spy Annotation
As the name suggests, you can use the @Spy annotation for spying on an object. Check out the following example.
package com.journaldev.mockito.mock;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
public class MockitoSpyAnnotationExample {
@Spy
Utils mockUtils;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
when(mockUtils.process(1, 1)).thenReturn(5);
//mocked method
assertEquals(5, mockUtils.process(1, 1));
//real method called since it's not stubbed
assertEquals(20, mockUtils.process(19, 1));
}
}
class Utils{
public int process(int x, int y) {
System.out.println("Input Params = "+x+","+y);
return x+y;
}
}
7. ToDoBusinessMock.java Example
Check out the following piece of code to see how you can use ToDoBusinessMock.java:
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class ToDoBusinessMock {
@Test
public void testusing_Mocks() {
ToDoService doService = mock(ToDoService.class);
List<String> combinedlist = Arrays.asList(" Use Core Java
", " Use Spring Core ", " Use w3eHibernate ", " Use Spring MVC ");
when(doService.getTodos("dummy")).thenReturn(combinedlist);
ToDoBusiness business = new ToDoBusiness(doService);
List<String> alltd = business.getTodosforHibernate("dummy");
System.out.println(alltd);
assertEquals(1, alltd.size());
}
}
8. Using TestList.java
This is very helpful for mocking a list class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.Test;
import org.mockito.Mock;
public class TestList {
@Test
public void testList_ReturnsSingle_value() {
List mocklist = mock(List.class);
when(mocklist.size()).thenReturn(1);
assertEquals(1, mocklist.size());
assertEquals(1, mocklist.size());
System.out.println( mocklist.size());
System.out.println(mocklist);
}
}
10. How To Get Multiple Return Values For A Test
You can also mock a list class with multiple return values. The list in the following example contains three items.
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.Test;
import org.mockito.Mock;
public class TestList {
@Test
public void testList_Returns_MultipleValues() {
List mocklist = mock(List.class);
when(mocklist.size()).thenReturn(1).thenReturn(2).thenReturn(3);
assertEquals(1, mocklist.size());
assertEquals(2, mocklist.size());
assertEquals(3, mocklist.size());
System.out.println(mocklist.size());
System.out.println(mocklist);
}
}
Conclusion
If you liked this list of 10 examples of Mockito in Java, feel free to share it with your friends and family.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.