Mockito Tutorial - Basics
What is Mockito?
Mockito is mocking frame work for Java Objects.
Why do we need to Mock Objects?
When an unit of code depended upon object that will not be available during test or development. We can create a mock object of it.
What is Mock Object?
A mock object is a dummy implementation for an interface or a class in which you define the output of certain method calls
Mockito Maven Dependency ?
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
Lets try to Mock a object of Math class that was not avilable during development.
Math.java
01 package com.tut.mockito;
02
03 /**
04 * Performs various Math Operations like addition,multiplication and division ..etc
05 *
06 */
07 public class Math {
08 // addition of two numbers
09 public int add(int a, int b) {
10 return a + b;
11 }
12
13 // Multiply two numbers
14 public int mul(int a, int b) {
15 return a * b;
16 }
17
18 // Division of two numbers
19 public int div(int a, int b) {
20 return a / b;
21 }
22
23 //Return a prime number
24 public int primeNumber(){
25 return 5;
26 }
27 }
Explanation: The above Math class has addition,multiplication,division as functions.
MathAddTestWithOutMock.java is a unit test cases that test add method on Math Object
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04
05 import org.junit.Before;
06 import org.junit.Test;
07
08 import com.tut.mockito.Math;
09
10 /**
11 * Test the add method of Math object
12 */
13 public class MathAddTestWithOutMock {
14 Math mathObj;
15
16 @Before
17 /**
18 * Create Math object before you use them
19 */
20 public void create() {
21 mathObj = new Math();//create a math object
22 }
23
24 @Test
25 public void test() {
26 assertSame(3, mathObj.add(1, 2)); // Assert that math object return 3
27 }
28
29 }
Explanation: In the above example we try to test add method. Often In the Test Driven Development we will not have Math class before we write tests around it. The approach we have to take is Mock the Math object and write the tests using Mocked object.
MathMockAddTest.java Tests the add method of Math class by mocking Math Object
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.mock;
05 import static org.mockito.Mockito.when;
06
07 import org.junit.Before;
08 import org.junit.Test;
10 import com.tut.mockito.Math;
11
12 /**
13 * Test the add method of Math object
14 */
15 public class MathMockAddTest {
16 Math mathObj; //The object that needs to mocked
17
18 @Before
19 /**
20 * Create mock object before you use them
21 */
22 public void create(){
23 mathObj= mock(Math.class); //Create Math mock Object
24 when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
25 }
26
27 @Test
28 public void test() {
29 assertSame(3, mathObj.add(1,2)); //Assert that math object return 3
30 }
31
32 }
Explanation: In the above code the static method mock is going to create mock object of Math class. The static method when defines the behavior of add method. (i.e) When some one called add method with arguments 1 and 2 return 3 as output. Note: Please bear in mind. MathMockAddTest is never creating a Math concrete object it is only creating Math mock object.
MathMockAddTestWithAnnotation.java Creates a mock object with Mockito Annotations
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.when;
05 import static org.mockito.MockitoAnnotations.initMocks;
07 import org.junit.Before;
08 import org.junit.Test;
09 import org.mockito.Mock;
11 import com.tut.mockito.Math;
13 /**
14 * Test the add method of Math object with Mockito annotation
15 */
16 public class MathMockAddTestWithAnnotation {
17 @Mock
18 Math mathObj;
19
20 @Before
21 /**
22 * Create mock object before you use them
23 */
24 public void create(){
25 initMocks(this);// Initialize this mock objects
26 when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
27 }
28
29 @Test
30 public void test() {
31 assertSame(3, mathObj.add(1,2));//Assert that math object return 3
32 }
33
34 }
Explanation:In the above example @Mock annotation is used to mock Math object. The static method initMocks initializes the mock objects in current class. Rest the behavior defined is same.
MathMockMulTest.java Test the multiplication method in Math class
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.*;
06 import org.junit.Before;
07 import org.junit.Test;
09 import com.tut.mockito.Math;
11 /**
12 * Test multiply function
13 */
14 public class MathMockMulTest {
15 Math mathObj;
16
17 @Before
18 public void create(){
19 mathObj= mock(Math.class);
20 when(mathObj.mul(anyInt(), eq(0))).thenReturn(0); //Multiply any number with zero. The function should return zero
21 }
23 @Test
24 /**
25 * Test the Multiply function in math object return zero if one of the argument is zero
26 */
27 public void test() {
28 assertSame(mathObj.mul(1,0),0);
29 assertSame(mathObj.mul(3,0),0);
30 }
32 }
Explanation:In the above example the static method anyInt accepts any argument as input and static method eq checks that the argument is zero.
MathMockDivTestWithException.java test the exception returned by div method in Math class.
01 package test.com.tut.mockito;
02
03 import static org.mockito.Matchers.anyInt;
04 import static org.mockito.Matchers.eq;
05 import static org.mockito.Mockito.mock;
06 import static org.mockito.Mockito.when;
08 import org.junit.Before;
09 import org.junit.Test;
11 import com.tut.mockito.Math;
13 /**
14 * Test division method of Math class
15 */
16 public class MathMockDivTestWithException {
17 Math mathObj;
18
19 @Before
20 public void create(){
21 mathObj= mock(Math.class); //Create Math Object
22 when(mathObj.div(anyInt(), eq(0))).thenThrow(new ArithmeticException()); // Configure it to return exception when denominator is zero
23 }
24
25 @Test(expected=ArithmeticException.class) //expect the method throws ArithmeticException
26 public void test() {
27 mathObj.div(1,0); //call the div and expect to return ArithmeticException
28 }
29
30 }
Explanation: The static method thenThrow should throw exception when denominator is zero.
MathMockPrimeNumTestWhichIsAMethodWithOutParameters.java Test a primeNumber method that doesn't take any argument
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.mock;
05 import static org.mockito.Mockito.when;
06
07 import org.junit.Before;
08 import org.junit.Test;
09
10 import com.tut.mockito.Math;
11
12 //Test a method that doesn't take any argument
13 public class MathMockPrimeNumTestWhichIsAMethodWithOutParameters{
14 Math mathObj;
15
16 @Before
17 public void create(){
18 mathObj= mock(Math.class); //Create Math Object
19 when(mathObj.primeNumber()).thenReturn(5); // Configure it to return 5 as prime number
20 }
22 @Test
23 public void test() {
24 assertSame(5, mathObj.primeNumber());
25 }
27 }
Explanation: In the above example when method primeNumber() is called the mock object will return 5
MathMockVerfiyTest.java Some times it is important to verify whether certain method on the object is called or called how many times. In such case we can use static method verify.
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.*;
05
06 import org.junit.Before;
07 import org.junit.Test;
08
09 import com.tut.mockito.Math;
10
12 public class MathMockVerfiyTest {
13 Math mathObj;
14
15 @Before
16 public void create(){
17 mathObj= mock(Math.class);
18 when(mathObj.add(1,2)).thenReturn(3);
19 }
20
21 @Test
22 public void test() {
23 //call the add function with 1,2 as arguments
24 assertSame(mathObj.add(1,2),3);
25
26 //Verify whether add method is tested with arguments 1,2
27 verify(mathObj).add(eq(1), eq(2));
28
29 //Verify whether add method is called only once
30 verify(mathObj,times(1)).add(1,2);
31 }
32
33 }
Explanation: In the above example we try to assert that add method is called with arguments 1,2 and it is called only once. That can be achieved using verify method.
Mockito Tutorial - Spring and Mockito Integration.
In the below example we use Calcuator Obect which computes the area of Rectangle using Rectangle Objects.
Frame works used
Spring -Dependency Injection
Mockito- Mocking java Obejcts
JUnit- Unit Test frame work.
CalculatorTestWithSpringAndMockito.java
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertEquals;
04 import static org.mockito.Mockito.when;
05 import static org.mockito.MockitoAnnotations.initMocks;
06
07 import org.junit.Before;
08 import org.junit.Test;
09 import org.junit.runner.RunWith;
10 import org.mockito.InjectMocks;
11 import org.mockito.Mock;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.test.context.ContextConfiguration;
14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
15
16 import com.tut.mockito.Calculator;
17 import com.tut.mockito.Rectangle;
18
19 @ContextConfiguration(locations = { "classpath:/beans.xml" })
20 @RunWith(SpringJUnit4ClassRunner.class)
21 public class CalculatorTestWithSpringAndMockito {
22
23 @Mock
24 Rectangle rectangle;
25
26 @InjectMocks
27 @Autowired
28 Calculator calculator;
29
30 @Before
31 public void create() {
32 initMocks(this);// Initialize this mock objects
33 when(rectangle.getLength()).thenReturn(10);
34 when(rectangle.getBreadth()).thenReturn(40);
35 }
36
37 @Test
38 public void test() {
39 assertEquals(calculator.getArea(), 400);
40 }
41
42 }
Explanation: In the above example the mocked rectangle object is injected into calculator object. @InjectMocks annotation of Mockito inject mocked rectangle object into calculator bean. The annotation @RunWith makes the class is runned with SpringJUnit4ClassRunner. The annotation ContextConfiguration specifies the path of spring bean definition.
Calculator.java
01 package com.tut.mockito;
02
03 public class Calculator {
04 private Rectangle rectangle;
05
06 public Rectangle getRectangle() {
07 return rectangle;
08 }
09
10 public void setRectangle(Rectangle rectangle) {
11 this.rectangle = rectangle;
12 }
13
14 public int getArea() {
15 return rectangle.getLength() * rectangle.getBreadth();
16 }
17
18 }
Rectangle.java
01 package com.tut.mockito;
02
03 public class Rectangle {
04 public int length;
05 public int breadth;
06
07 public int getLength() {
08 return length;
09 }
10
11 public void setLength(int length) {
12 this.length = length;
13 }
14
15 public int getBreadth() {
16 return breadth;
17 }
18
19 public void setBreadth(int breadth) {
20 this.breadth = breadth;
21 }
22
23 }
beans.xml
01 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
02 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
06 <bean class="com.tut.mockito.Calculator" id="calculator">
07 <property name="rectangle" ref="rectangle">
08 </property></bean>
09
10 <bean class="com.tut.mockito.Rectangle" id="rectangle">
11 <property name="length" value="10">
12 <property name="breadth" value="20">
13 </property></property></bean>
14
15 </beans>
Mockito - Testing DAO Layer
Book.java
import java.util.List;
/**
* Model class for the book details.
*/
public class Book {
private String isbn;
private String title;
private List<String> authors;
private String publication;
private Integer yearOfPublication;
private Integer numberOfPages;
private String image;
public Book(String isbn,
String title,
List<String> authors,
String publication,
Integer yearOfPublication,
Integer numberOfPages,
String image){
this.isbn = isbn;
this.title = title;
this.authors = authors;
this.publication = publication;
this.yearOfPublication = yearOfPublication;
this.numberOfPages = numberOfPages;
this.image = image;
}
public String getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public List<String> getAuthors() {
return authors;
}
public String getPublication() {
return publication;
}
public Integer getYearOfPublication() {
return yearOfPublication;
}
public Integer getNumberOfPages() {
return numberOfPages;
}
public String getImage() {
return image;
}
}
BookDAL.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* API layer for persisting and retrieving the Book objects.
*/
public class BookDAL {
private static BookDAL bookDAL = new BookDAL();
public List<Book> getAllBooks(){
return Collections.EMPTY_LIST;
}
public Book getBook(String isbn){
return null;
}
public String addBook(Book book){
return book.getIsbn();
}
public String updateBook(Book book){
return book.getIsbn();
}
public static BookDAL getInstance(){
return bookDAL;
}
}
pom.xml
<dependencies>
<!-- Dependency for JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Dependency for Mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
BookDALTest.java
public class BookDALTest {
public void setUp() throws Exception {
}
public void testGetAllBooks() throws Exception {
}
public void testGetBook() throws Exception {
}
public void testAddBook() throws Exception {
}
public void testUpdateBook() throws Exception {
}
}
Modified BookDALTest.java
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
public class BookDALTest {
private static BookDAL mockedBookDAL;
private static Book book1;
private static Book book2;
@BeforeClass
public static void setUp(){
mockedBookDAL = mock(BookDAL.class);
book1 = new Book("8131721019","Compilers Principles",
Arrays.asList("D. Jeffrey Ulman","Ravi Sethi", "Alfred V. Aho", "Monica S. Lam"),
"Pearson Education Singapore Pte Ltd", 2008,1009,"BOOK_IMAGE");
book2 = new Book("9788183331630","Let Us C 13th Edition",
Arrays.asList("Yashavant Kanetkar"),"BPB PUBLICATIONS", 2012,675,"BOOK_IMAGE");
when(mockedBookDAL.getAllBooks()).thenReturn(Arrays.asList(book1, book2));
when(mockedBookDAL.getBook("8131721019")).thenReturn(book1);
when(mockedBookDAL.addBook(book1)).thenReturn(book1.getIsbn());
when(mockedBookDAL.updateBook(book1)).thenReturn(book1.getIsbn());
}
@Test
public void testGetAllBooks() throws Exception {
List<Book> allBooks = mockedBookDAL.getAllBooks();
assertEquals(2, allBooks.size());
Book myBook = allBooks.get(0);
assertEquals("8131721019", myBook.getIsbn());
assertEquals("Compilers Principles", myBook.getTitle());
assertEquals(4, myBook.getAuthors().size());
assertEquals((Integer)2008, myBook.getYearOfPublication());
assertEquals((Integer) 1009, myBook.getNumberOfPages());
assertEquals("Pearson Education Singapore Pte Ltd", myBook.getPublication());
assertEquals("BOOK_IMAGE", myBook.getImage());
}
@Test
public void testGetBook(){
String isbn = "8131721019";
Book myBook = mockedBookDAL.getBook(isbn);
assertNotNull(myBook);
assertEquals(isbn, myBook.getIsbn());
assertEquals("Compilers Principles", myBook.getTitle());
assertEquals(4, myBook.getAuthors().size());
assertEquals("Pearson Education Singapore Pte Ltd", myBook.getPublication());
assertEquals((Integer)2008, myBook.getYearOfPublication());
assertEquals((Integer)1009, myBook.getNumberOfPages());
}
@Test
public void testAddBook(){
String isbn = mockedBookDAL.addBook(book1);
assertNotNull(isbn);
assertEquals(book1.getIsbn(), isbn);
}
@Test
public void testUpdateBook(){
String isbn = mockedBookDAL.updateBook(book1);
assertNotNull(isbn);
assertEquals(book1.getIsbn(), isbn);
}
}
What is Mockito?
Mockito is mocking frame work for Java Objects.
Why do we need to Mock Objects?
When an unit of code depended upon object that will not be available during test or development. We can create a mock object of it.
What is Mock Object?
A mock object is a dummy implementation for an interface or a class in which you define the output of certain method calls
Mockito Maven Dependency ?
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
Lets try to Mock a object of Math class that was not avilable during development.
Math.java
01 package com.tut.mockito;
02
03 /**
04 * Performs various Math Operations like addition,multiplication and division ..etc
05 *
06 */
07 public class Math {
08 // addition of two numbers
09 public int add(int a, int b) {
10 return a + b;
11 }
12
13 // Multiply two numbers
14 public int mul(int a, int b) {
15 return a * b;
16 }
17
18 // Division of two numbers
19 public int div(int a, int b) {
20 return a / b;
21 }
22
23 //Return a prime number
24 public int primeNumber(){
25 return 5;
26 }
27 }
Explanation: The above Math class has addition,multiplication,division as functions.
MathAddTestWithOutMock.java is a unit test cases that test add method on Math Object
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04
05 import org.junit.Before;
06 import org.junit.Test;
07
08 import com.tut.mockito.Math;
09
10 /**
11 * Test the add method of Math object
12 */
13 public class MathAddTestWithOutMock {
14 Math mathObj;
15
16 @Before
17 /**
18 * Create Math object before you use them
19 */
20 public void create() {
21 mathObj = new Math();//create a math object
22 }
23
24 @Test
25 public void test() {
26 assertSame(3, mathObj.add(1, 2)); // Assert that math object return 3
27 }
28
29 }
Explanation: In the above example we try to test add method. Often In the Test Driven Development we will not have Math class before we write tests around it. The approach we have to take is Mock the Math object and write the tests using Mocked object.
MathMockAddTest.java Tests the add method of Math class by mocking Math Object
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.mock;
05 import static org.mockito.Mockito.when;
06
07 import org.junit.Before;
08 import org.junit.Test;
10 import com.tut.mockito.Math;
11
12 /**
13 * Test the add method of Math object
14 */
15 public class MathMockAddTest {
16 Math mathObj; //The object that needs to mocked
17
18 @Before
19 /**
20 * Create mock object before you use them
21 */
22 public void create(){
23 mathObj= mock(Math.class); //Create Math mock Object
24 when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
25 }
26
27 @Test
28 public void test() {
29 assertSame(3, mathObj.add(1,2)); //Assert that math object return 3
30 }
31
32 }
Explanation: In the above code the static method mock is going to create mock object of Math class. The static method when defines the behavior of add method. (i.e) When some one called add method with arguments 1 and 2 return 3 as output. Note: Please bear in mind. MathMockAddTest is never creating a Math concrete object it is only creating Math mock object.
MathMockAddTestWithAnnotation.java Creates a mock object with Mockito Annotations
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.when;
05 import static org.mockito.MockitoAnnotations.initMocks;
07 import org.junit.Before;
08 import org.junit.Test;
09 import org.mockito.Mock;
11 import com.tut.mockito.Math;
13 /**
14 * Test the add method of Math object with Mockito annotation
15 */
16 public class MathMockAddTestWithAnnotation {
17 @Mock
18 Math mathObj;
19
20 @Before
21 /**
22 * Create mock object before you use them
23 */
24 public void create(){
25 initMocks(this);// Initialize this mock objects
26 when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
27 }
28
29 @Test
30 public void test() {
31 assertSame(3, mathObj.add(1,2));//Assert that math object return 3
32 }
33
34 }
Explanation:In the above example @Mock annotation is used to mock Math object. The static method initMocks initializes the mock objects in current class. Rest the behavior defined is same.
MathMockMulTest.java Test the multiplication method in Math class
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.*;
06 import org.junit.Before;
07 import org.junit.Test;
09 import com.tut.mockito.Math;
11 /**
12 * Test multiply function
13 */
14 public class MathMockMulTest {
15 Math mathObj;
16
17 @Before
18 public void create(){
19 mathObj= mock(Math.class);
20 when(mathObj.mul(anyInt(), eq(0))).thenReturn(0); //Multiply any number with zero. The function should return zero
21 }
23 @Test
24 /**
25 * Test the Multiply function in math object return zero if one of the argument is zero
26 */
27 public void test() {
28 assertSame(mathObj.mul(1,0),0);
29 assertSame(mathObj.mul(3,0),0);
30 }
32 }
Explanation:In the above example the static method anyInt accepts any argument as input and static method eq checks that the argument is zero.
MathMockDivTestWithException.java test the exception returned by div method in Math class.
01 package test.com.tut.mockito;
02
03 import static org.mockito.Matchers.anyInt;
04 import static org.mockito.Matchers.eq;
05 import static org.mockito.Mockito.mock;
06 import static org.mockito.Mockito.when;
08 import org.junit.Before;
09 import org.junit.Test;
11 import com.tut.mockito.Math;
13 /**
14 * Test division method of Math class
15 */
16 public class MathMockDivTestWithException {
17 Math mathObj;
18
19 @Before
20 public void create(){
21 mathObj= mock(Math.class); //Create Math Object
22 when(mathObj.div(anyInt(), eq(0))).thenThrow(new ArithmeticException()); // Configure it to return exception when denominator is zero
23 }
24
25 @Test(expected=ArithmeticException.class) //expect the method throws ArithmeticException
26 public void test() {
27 mathObj.div(1,0); //call the div and expect to return ArithmeticException
28 }
29
30 }
Explanation: The static method thenThrow should throw exception when denominator is zero.
MathMockPrimeNumTestWhichIsAMethodWithOutParameters.java Test a primeNumber method that doesn't take any argument
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.mock;
05 import static org.mockito.Mockito.when;
06
07 import org.junit.Before;
08 import org.junit.Test;
09
10 import com.tut.mockito.Math;
11
12 //Test a method that doesn't take any argument
13 public class MathMockPrimeNumTestWhichIsAMethodWithOutParameters{
14 Math mathObj;
15
16 @Before
17 public void create(){
18 mathObj= mock(Math.class); //Create Math Object
19 when(mathObj.primeNumber()).thenReturn(5); // Configure it to return 5 as prime number
20 }
22 @Test
23 public void test() {
24 assertSame(5, mathObj.primeNumber());
25 }
27 }
Explanation: In the above example when method primeNumber() is called the mock object will return 5
MathMockVerfiyTest.java Some times it is important to verify whether certain method on the object is called or called how many times. In such case we can use static method verify.
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertSame;
04 import static org.mockito.Mockito.*;
05
06 import org.junit.Before;
07 import org.junit.Test;
08
09 import com.tut.mockito.Math;
10
12 public class MathMockVerfiyTest {
13 Math mathObj;
14
15 @Before
16 public void create(){
17 mathObj= mock(Math.class);
18 when(mathObj.add(1,2)).thenReturn(3);
19 }
20
21 @Test
22 public void test() {
23 //call the add function with 1,2 as arguments
24 assertSame(mathObj.add(1,2),3);
25
26 //Verify whether add method is tested with arguments 1,2
27 verify(mathObj).add(eq(1), eq(2));
28
29 //Verify whether add method is called only once
30 verify(mathObj,times(1)).add(1,2);
31 }
32
33 }
Explanation: In the above example we try to assert that add method is called with arguments 1,2 and it is called only once. That can be achieved using verify method.
Mockito Tutorial - Spring and Mockito Integration.
In the below example we use Calcuator Obect which computes the area of Rectangle using Rectangle Objects.
Frame works used
Spring -Dependency Injection
Mockito- Mocking java Obejcts
JUnit- Unit Test frame work.
CalculatorTestWithSpringAndMockito.java
01 package test.com.tut.mockito;
02
03 import static org.junit.Assert.assertEquals;
04 import static org.mockito.Mockito.when;
05 import static org.mockito.MockitoAnnotations.initMocks;
06
07 import org.junit.Before;
08 import org.junit.Test;
09 import org.junit.runner.RunWith;
10 import org.mockito.InjectMocks;
11 import org.mockito.Mock;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.test.context.ContextConfiguration;
14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
15
16 import com.tut.mockito.Calculator;
17 import com.tut.mockito.Rectangle;
18
19 @ContextConfiguration(locations = { "classpath:/beans.xml" })
20 @RunWith(SpringJUnit4ClassRunner.class)
21 public class CalculatorTestWithSpringAndMockito {
22
23 @Mock
24 Rectangle rectangle;
25
26 @InjectMocks
27 @Autowired
28 Calculator calculator;
29
30 @Before
31 public void create() {
32 initMocks(this);// Initialize this mock objects
33 when(rectangle.getLength()).thenReturn(10);
34 when(rectangle.getBreadth()).thenReturn(40);
35 }
36
37 @Test
38 public void test() {
39 assertEquals(calculator.getArea(), 400);
40 }
41
42 }
Explanation: In the above example the mocked rectangle object is injected into calculator object. @InjectMocks annotation of Mockito inject mocked rectangle object into calculator bean. The annotation @RunWith makes the class is runned with SpringJUnit4ClassRunner. The annotation ContextConfiguration specifies the path of spring bean definition.
Calculator.java
01 package com.tut.mockito;
02
03 public class Calculator {
04 private Rectangle rectangle;
05
06 public Rectangle getRectangle() {
07 return rectangle;
08 }
09
10 public void setRectangle(Rectangle rectangle) {
11 this.rectangle = rectangle;
12 }
13
14 public int getArea() {
15 return rectangle.getLength() * rectangle.getBreadth();
16 }
17
18 }
Rectangle.java
01 package com.tut.mockito;
02
03 public class Rectangle {
04 public int length;
05 public int breadth;
06
07 public int getLength() {
08 return length;
09 }
10
11 public void setLength(int length) {
12 this.length = length;
13 }
14
15 public int getBreadth() {
16 return breadth;
17 }
18
19 public void setBreadth(int breadth) {
20 this.breadth = breadth;
21 }
22
23 }
beans.xml
01 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
02 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
06 <bean class="com.tut.mockito.Calculator" id="calculator">
07 <property name="rectangle" ref="rectangle">
08 </property></bean>
09
10 <bean class="com.tut.mockito.Rectangle" id="rectangle">
11 <property name="length" value="10">
12 <property name="breadth" value="20">
13 </property></property></bean>
14
15 </beans>
Mockito - Testing DAO Layer
Book.java
import java.util.List;
/**
* Model class for the book details.
*/
public class Book {
private String isbn;
private String title;
private List<String> authors;
private String publication;
private Integer yearOfPublication;
private Integer numberOfPages;
private String image;
public Book(String isbn,
String title,
List<String> authors,
String publication,
Integer yearOfPublication,
Integer numberOfPages,
String image){
this.isbn = isbn;
this.title = title;
this.authors = authors;
this.publication = publication;
this.yearOfPublication = yearOfPublication;
this.numberOfPages = numberOfPages;
this.image = image;
}
public String getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public List<String> getAuthors() {
return authors;
}
public String getPublication() {
return publication;
}
public Integer getYearOfPublication() {
return yearOfPublication;
}
public Integer getNumberOfPages() {
return numberOfPages;
}
public String getImage() {
return image;
}
}
BookDAL.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* API layer for persisting and retrieving the Book objects.
*/
public class BookDAL {
private static BookDAL bookDAL = new BookDAL();
public List<Book> getAllBooks(){
return Collections.EMPTY_LIST;
}
public Book getBook(String isbn){
return null;
}
public String addBook(Book book){
return book.getIsbn();
}
public String updateBook(Book book){
return book.getIsbn();
}
public static BookDAL getInstance(){
return bookDAL;
}
}
pom.xml
<dependencies>
<!-- Dependency for JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Dependency for Mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
BookDALTest.java
public class BookDALTest {
public void setUp() throws Exception {
}
public void testGetAllBooks() throws Exception {
}
public void testGetBook() throws Exception {
}
public void testAddBook() throws Exception {
}
public void testUpdateBook() throws Exception {
}
}
Modified BookDALTest.java
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
public class BookDALTest {
private static BookDAL mockedBookDAL;
private static Book book1;
private static Book book2;
@BeforeClass
public static void setUp(){
mockedBookDAL = mock(BookDAL.class);
book1 = new Book("8131721019","Compilers Principles",
Arrays.asList("D. Jeffrey Ulman","Ravi Sethi", "Alfred V. Aho", "Monica S. Lam"),
"Pearson Education Singapore Pte Ltd", 2008,1009,"BOOK_IMAGE");
book2 = new Book("9788183331630","Let Us C 13th Edition",
Arrays.asList("Yashavant Kanetkar"),"BPB PUBLICATIONS", 2012,675,"BOOK_IMAGE");
when(mockedBookDAL.getAllBooks()).thenReturn(Arrays.asList(book1, book2));
when(mockedBookDAL.getBook("8131721019")).thenReturn(book1);
when(mockedBookDAL.addBook(book1)).thenReturn(book1.getIsbn());
when(mockedBookDAL.updateBook(book1)).thenReturn(book1.getIsbn());
}
@Test
public void testGetAllBooks() throws Exception {
List<Book> allBooks = mockedBookDAL.getAllBooks();
assertEquals(2, allBooks.size());
Book myBook = allBooks.get(0);
assertEquals("8131721019", myBook.getIsbn());
assertEquals("Compilers Principles", myBook.getTitle());
assertEquals(4, myBook.getAuthors().size());
assertEquals((Integer)2008, myBook.getYearOfPublication());
assertEquals((Integer) 1009, myBook.getNumberOfPages());
assertEquals("Pearson Education Singapore Pte Ltd", myBook.getPublication());
assertEquals("BOOK_IMAGE", myBook.getImage());
}
@Test
public void testGetBook(){
String isbn = "8131721019";
Book myBook = mockedBookDAL.getBook(isbn);
assertNotNull(myBook);
assertEquals(isbn, myBook.getIsbn());
assertEquals("Compilers Principles", myBook.getTitle());
assertEquals(4, myBook.getAuthors().size());
assertEquals("Pearson Education Singapore Pte Ltd", myBook.getPublication());
assertEquals((Integer)2008, myBook.getYearOfPublication());
assertEquals((Integer)1009, myBook.getNumberOfPages());
}
@Test
public void testAddBook(){
String isbn = mockedBookDAL.addBook(book1);
assertNotNull(isbn);
assertEquals(book1.getIsbn(), isbn);
}
@Test
public void testUpdateBook(){
String isbn = mockedBookDAL.updateBook(book1);
assertNotNull(isbn);
assertEquals(book1.getIsbn(), isbn);
}
}