Mockito and mockmockito

Source: Internet
Author: User
Tags maven central

Mockito and mockmockito

During the write unit test process in the actual project, we will find that the classes to be tested have many dependencies, and these dependencies have dependencies, which makes building impossible in the unit test code, in particular, unit tests cannot be carried out when the dependencies have not been built. To solve these problems, we have introduced the Mock concept. Simply put, we simulate the classes or resources to be built and provide them to the objects to be tested. There are many Mock tools in the industry, and they are very mature. Here we will directly use the most popular Mockito for practical drills.

Mock tool Overview 1.1 Introduction to Mockito

 

EasyMock and Mockito are applied to their work by many people because they can greatly simplify the unit test writing process, however, none of these Mock tools can simulate static functions, constructors, private functions, Final functions, and system functions, however, these methods are often the functions we need in large systems.

For more details about the new features of Mockito2.0, refer to the official introduction documents for the following reasons:

Https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2

1.2 Mockito preparation

### Maven ###

For Maven management, you need to add the following dependencies to the project Pom. xml:

 <dependencies><dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>2.7.19</version><scope>test</scope></dependency></dependencies>

 

 

In the program, you can import org. mockito. Mockito and then call its static method.

Maven users can declare dependencies on mockito-core. Mockito is automatically released to the Bintray center and synchronized to Maven Central Repository.

Note: You can use 1. * "mockito-all" to distribute the Legacy build with manual dependency management. It can be downloaded from the Mockito Bintray repository or from the Bintray center. However, the Mockito 2. * "mockito-all" release has been stopped, and Mockito 2 and later versions use "mockito-core ".

Download center on the official website:

Http://search.maven.org/#search | gav | 1 | g % 3A % 22org. mockito % 22% 20AND % 20a % 3A % 22mockito-core % 22

The latest version is 2.7.19. Due to Network Gateway problems, it is best to download it manually from the official website.

In addition, Mockito needs to be used together with Junit, which is also introduced in the Pom file:

<dependency>        <groupId>junit</groupId>        <artifactId>junit</artifactId>        <version>4.12</version>        <scope>test</scope>      </dependency>

Then, in order to make the code more concise, it is best to import static Resources in the Test class, and to use the common junit keywords, we also need to introduce the two junit classes Before and Test:

import static org.mockito.Mockito.*;import static org.junit.Assert.*;import org.junit.Before;import org.junit.Test;
1.3 Simulated Object

The syntax for creating a Mock object is mock (class or interface ).

Create a Mock object

mock(Class classToMock); mock(Class classToMock, String name) mock(Class classToMock, Answer defaultAnswer) mock(Class classToMock, MockSettings mockSettings) mock(Class classToMock, ReturnValues returnValues)

You can create mock objects for classes and interfaces. You can name mock objects during creation. The advantage of mock object naming is that it is easy to recognize mock objects during debugging.

 

Mock object's expected behavior and return value settings

Suppose we have created the mock object of the sort list class:

Required list mockedList = mock (required list. class );

1.4 set the expected return value of an object call

Use when (mock. someMethod (). thenReturn (value) to set the return value of a Mock object when calling a method. Let's take a look at the notes about the thenReturn method in the source code:

 

Use the when (mock. someMethod (). thenThrow (new RuntimeException) method to set the exception thrown when a method is called.

 

And Answer:

 

 

Answer is a generic interface. This callback will be executed when the call occurs, through Object [] args = invocation. getArguments (); get the parameters passed in during the call, through Object mock = invocation. getMock (); you can get the mock object.

Some methods may use the interface parameter as a Listener parameter. If we use Answer, we can obtain this Listener and execute the corresponding callback function in the Answer function, this helps us understand the internal execution of functions.

Using doThrow (new RuntimeException ("clear exception"). when (mockedList). clear (); mockedList. clear (); Mock functions with no return value type:

DoThrow (new RuntimeException (). when (mockedList). clear ();

// RuntimeException will be thrown:

MockedList. clear ();

This instance indicates that RuntimeException will be thrown when mockedList. clear () is executed. Other doXXX execution is similar to that of it.

For example: doReturn () | doThrow () | doAnswer () | doNothing () | doCallRealMethod () methods.

 

Spy functions:

You can create a monitoring (spy) object for a real object. When you use this spy object, the real object will also be called unless its function is piling up. You should try to use as few spy objects as possible and be careful when using them. For example, the spy object can be used to process legacy code. The Spy example is as follows:

List list = new Functions List (); // monitors a real object list spy = spy (List); // You can pile up some functions when (spy. size ()). thenReturn (100); // use this to call the function spy of the real object. add ("one"); spy. add ("two"); // print "one" System. out. println (spy. get (0); // size () will print 100System. out. println (spy. size (); // interactive verification verify (spy ). add ("one"); verify (spy ). add ("two ");

It is very important to understand the real objects of monitoring. Sometimes, it is impossible or impractical to use when (Object) on monitoring objects. Because when using a monitoring object, consider using the doReturn, Answer, Throw () function group for piling. For example:

List list = new vertex List ();

List spy = spy (list );

// This is not possible: When you call spy. get (0), the get (0) function of the real object is called.

// IndexOutOfBoundsException exception, because the real object is empty when (spy. get (0). thenReturn ("foo ");

// You need to use doReturn () for piling

DoReturn ("foo"). when (spy). get (0 );

Mockito does not call the real object proxy function. In fact, it will copy the real object. Therefore, if you keep the real object and interact with it, do not expect the Monitored object to get the correct result. When you call a function without stub on a monitoring object, it does not call the corresponding function of the real object, and you do not see any effect on the real object.

1.5 verify the tested method

Once a Mock object is created, its interaction behavior is automatically recorded, so we can choose to verify its interaction behavior. In Mockito, verify (Mock). someMethod (…) is used to verify the interaction behavior of the mock object (...). Finally, Assert () verifies whether the returned value is the same as expected.

1.6 Demo

Find the simplest code instance from the Internet. The following Code demonstrates how to use Mockito. The Code has three classes:

Person class:

public class Person {    private final int id;     private final String name;     public Person(int id, String name) {         this.id = id;         this.name = name;         }     public int getId() {         return id;         }     public String getName() {         return name;         }}

PersonDao class:

public interface PersonDao {    Person getPerson(int id);     boolean update(Person person);     }

PersonService class:

 

public class PersonService {    private final PersonDao personDao;     public PersonService(PersonDao personDao) {         this.personDao = personDao;         }     public boolean update(int id, String name) {         Person person = personDao.getPerson(id);         if (person == null)         { return false; }         Person personUpdate = new Person(person.getId(), name);         return personDao.update(personUpdate);         }}

 

You can still use Junit to automatically generate a test class or manually create a test class:

 

 

After the test code is generated, delete the default assertfail and enter the following two testing methods:

Import org. junit. before; import org. junit. test; import static org. junit. assert. *; import static org. mockito. mockito. *; public class PersonServiceTest {private PersonDao mockDao; private PersonService personService; @ Before public void setUp () throws Exception {// simulate the PersonDao object mockDao = mock (PersonDao. class); when (mockDao. getPerson (1 )). thenReturn (new Person (1, "Person1"); when (mockDao. update (isA (Person. class ))). thenReturn (true); personService = new PersonService (mockDao);} @ Test public void testUpdate () throws Exception {boolean result = personService. update (1, "new name"); assertTrue ("must true", result); // verify whether getPerson (1) verify (mockDao, times (1 )). getPerson (eq (1); // verify whether an update verify (mockDao, times (1) has been executed )). update (isA (Person. class);} @ Test public void testUpdateNotFind () throws Exception {boolean result = personService. update (2, "new name"); assertFalse ("must true", result); // verify whether getPerson (1) verify (mockDao, times (1 )). getPerson (eq (1); // verify whether an update verify (mockDao, never () has been executed ()). update (isA (Person. class ));}}

Note: We perform mock on PersonDAO and set stubbing. stubbing settings are as follows:

  • When the getPerson method is passed in 1, a Person object is returned. Otherwise, null is returned by default.
  • Returns true when the update method is called.

The parameter matcher is used here:

IsA (): Object argument that implements the given class.

Eq (): int argument that is equal to the given value

Note: The concept of parameter matching is not described here.

 

Still calling Junit to execute the unit test code. Result:

Two cases are verified:

  • Update the name of Person with id 1. expected: the Person can be found in DAO and updated successfully.
  • Update the name of Person with id 2. Expected: the Person cannot be found in DAO. update failed.

You can also view the exception information thrown by Eclipse:

Argument (s) are different! Wanted:

PersonDao. getPerson (1 );

-> At PersonServiceTest. testUpdateNotFind (PersonServiceTest. java: 41)

Actual invocation has different arguments:

PersonDao. getPerson (2 );

-> At PersonService. update (PersonService. java: 8)

Unit 2 testing and coverage

1. Junit 2, jacco 3, and EclEmma

2 Coverage Rate

The coverage rate is shown as follows:

The coverage rate still uses jacco and EclEmma:

L marked as red without overwriting code

L The overwritten code is marked as green

L partially covered Code marked as yellow

You can also customize the color settings in Eclipse:

In the status bar window below Eclipse, There is a bar "Coverage". Click it to display detailed code Coverage:

How to export a Report in Html format:

Right-click the Coverage bar under Eclipse and choose "Export Session ...", In the pop-up window, select the export target as "Coverage Report", for example:

Click "Next" and select the session to be exported in the Next pop-up window. Format

Select "HTML report" as the type, and temporarily select the export location as the desktop. Click "Finish" to generate the export location.

A page named index.html is the Coverage Report generated just now:

Click a folder to go to the directory to further view the sub-file coverage rate:

 

 

Appendix: Reference document overview

 

Mockito Official Website: http://site.mockito.org/

Learn about Mockito: http://liuzhijun.iteye.com/blog/1512780 in 5 minutes

Mockito brief introduction and example: http://blog.csdn.net/huoshuxiao/article/details/6107835

Mockito discussion: http://www.jianshu.com/p/77db26b4fb54

Unit Testing Tool-Mockito documents: http://blog.csdn.net/bboyfeiyu/article/details/52127551

Mockito User Guide: http://blog.csdn.net/shensky711/article/details/52771493

JUnit + Mockito unit test (2): http://blog.csdn.net/zhangxin09/article/details/42422643

 

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.