"Translation" Java uses Mockito for mock testing

Source: Internet
Author: User

One of the great challenges we all face when writing unit tests is the dependency of modules on other components. Spending a lot of time and effort to configure a dependent component environment is a thankless task. Using mock is an efficient way to replace other components to continue our unit test build process.

Next I'll show you an example of using a mock technique. Here I have a data access layer (DAL) to create a class that provides the basic API for applications to access and modify data in the database. Then I'll test the DAL instance, but it's not really connected to the database. The purpose of using the Dal class is to help us isolate the application code and the data display layer.

Let's create a Java MAVEN project from the command line below.



mvn archetype:generate -DgroupId=info.sanaulla -DartifactId=MockitoDemo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

The above command creates a folder named Mockitodemo and the directory structure and test file for the corresponding entity class.

Please refer to the following example to create an entity class:



package info.sanaulla.models;

import java.util.List;

/**

  • Model class for the book details.

    */

    public class Book {

    Private String ISBN;

    Private String title;

    Private List 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 GetAuthors () {

    return authors;

    }

    Public String getpublication () {

    return publication;

    }

    Public Integer getyearofpublication () {

    return yearofpublication;

    }

    Public Integer getnumberofpages () {

    return numberofpages;

    }

    Public String GetImage () {

    return image;

    }

    }

The DAL classes used to manipulate the book class are as follows:



package info.sanaulla.dal;

import info.sanaulla.models.Book;

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 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;

    }

    }

The DAL layer now has no actual functionality, and I will try to build (TDD) in a test-driven development way. We do not care whether the DAL layer is data communication through entity relationship mapping or other database APIs to implement the above operations.

Data-driven data access layer

There are a lot of unit test frameworks and mock frames, where I choose the JUnit Unit Test framework and the Moke framework Mockito. We need to update their dependencies in the Pom.xml configuration file.

   <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:s chemalocation= "http://maven.apache.org/POM/4.0.0 <a href=" Http://maven.apache.org/maven-v4_0_0.xsd ">http:/ /maven.apache.org/maven-v4_0_0.xsd "</a>> <modelVersion>4.0.0</modelVersion> <groupId> Info.sanaulla</groupid> <artifactId>MockitoDemo</artifactId> <packaging>jar</ packaging> <version>1.0-SNAPSHOT</version> <name>MockitoDemo</name> <url>http:// Maven.apache.org</url> <dependencies> <!--Dependency for JUnit---<dependency> <g      Roupid>junit</groupid> <artifactId>junit</artifactId> <version>4.10</version>      <scope>test</scope> </dependency> <!--dependency for Mockito---<dependency> <groupId>org.mockito</groupId> &LT;ARTIFACtid>mockito-all</artifactid> <version>1.9.5</version> <scope>test</scope> &L T;/dependency> </dependencies></project>

Now we write the unit test class for Bookdal. With unit testing, we can inject mock objects into the Bookdal for unit testing without relying on other data sources.

First, create an empty test class with the following code:



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 {





In the following code, we inject the Bookdal object in a mock manner in the Setup method



public class Bookdaltest {

private static Bookdal Mockedbookdal;

private static book Book1;

private static book Book2;

@BeforeClass

public static void SetUp () {

//Create mock object of BookDALmockedBookDAL = mock(BookDAL.class);//Create few instances of Book 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");//Stubbing the methods of mocked BookDAL with mocked data. 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());

}

public void Testgetallbooks () throws Exception {}

public void Testgetbook () throws Exception {}

public void Testaddbook () throws Exception {}

public void testUpdateBook() throws Exception {}

}

In the Setup method I use the following way

1. Create an Bookdal instance:



BookDAL mockedBookDAL = mock(BookDAL.class);

A mock object of the Dal in the 2.Mokito API, using the When method to receive a method return value parameter that invokes a mock object.



//When getAllBooks() is invoked then return the given data and so on for the other methods.

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());

Implement the other already declared test methods:



Package info.sanaulla.dal;

Import Info.sanaulla.models.Book;

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

}

}

We then use MAVEN's command navigation: mvn test run the current project. The console output is as follows:



-——————————————————

T E S T S

-——————————————————

Running info.sanaulla.AppTest

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 sec

Running info.sanaulla.dal.BookDALTest

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.209 sec

Results :



Now we have implemented a mock object to test the Dal class, even if the data source is not configured.

Instance Code

Network address: Mockitodemo

"Translation" Java uses Mockito for mock testing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.