Introduction to mock simulation test and Mockito use

Source: Internet
Author: User

What is a Mock?

A mock test is a test method that is created in order to be tested with a virtual object for some objects that are not easily constructed or are not easily accessible during the test process. This virtual object is a mock object. Mock objects are substitutes for real objects during commissioning.

A simple look at a picture

When we test Class A, class A needs to call Class B and Class C, and Class B and Class C need to call other classes such as D, E, F, etc., if the classes D, E, F constructs are time-consuming, or call time-consuming, it is very inconvenient to test (for example, the DAO class, every time the database is accessed) So we're introducing Mock objects.

For example, we replace Class B and Class C with mock objects, and when we call methods of Class B and Class C, we replace them with the method of the mock object (of course we set the parameters and expected results ourselves) without actually invoking the other classes. This is a much higher test efficiency.

One sentence why mock: because we actually write the program is not a simple class, but a complex dependency of the class, Mock objects let us do not rely on the specific object of the case to complete the test.

Mock's key point mock object

The concept of a mock object is that we want to create an object that can replace the actual object, which can invoke a particular method through a specific parameter and return the expected result.

Stub (pile)

A pile refers to a program segment used to replace a specific function. The pile program can be used to simulate the behavior of an existing program or a temporary replacement for an unfinished development program.

For example, we have a function to get the temperature.

publicdoublegetTemperature(String Position) {    double ret = TemperatureRead(Position);}

But the Temperatureread function calls the specific hardware device, and the hardware device is not ready.

We can replace it with stubs.

publicdoubleTemperatureRead(String position) {    return28;}

Stub:for replacing a method with code that returns a specified result

Mock:a stub with a expectations that the method gets called

Set the expected

By setting what happens when an expected explicit Mock object executes, such as returning a specific value, throwing an exception, triggering an event, or invoking a certain number of times.

Verify the expected results

Setup expectations and validations are expected to be in parallel. The setting is expected to complete before the function of the test class is called, and the validation is expected after it. So, first you set the desired results and then verify that your expected results are correct.

The benefit of a Mock is what to create the test in advance; TDD (test-driven development)

That's the biggest benefit. If you create a mock then you can write the service tests before the service interface is created, so you can add the test to your automated test environment during the development process. In other words, impersonation enables you to use test-driven development.

Teams can work in parallel

This is similar to the point above; create tests for non-existent code. But what we're talking about is that the developers write the test program, which is the test team to create. How does the test team create tests when nothing is being measured? Simulate and test for simulations! This means that when the service excuse needs to be tested, the QA team actually has a complete set of test components, and no one team waits for the other team to finish. This makes the simulation of the benefits of particularly prominent.

You can create a validation or demo program

Because mocks is very efficient, mocks can be used to create a proof of concept, as one, or as a demo program that you are considering building a project. This provides a strong foundation for you to decide whether the project will be followed, but the most important is to provide practical design decisions.

Write Tests for inaccessible resources

This benefit does not belong to the actual benefit of a kind, but as a necessary when the "life buoy." Have you encountered such a situation? When you want to test a service interface, but the service needs to be accessed through a firewall, the firewall cannot be opened for you or you need authentication to access it. When this happens, you can use the Mockservice alternative where you can access it, which is a "life buoy" feature.

Mock can be handed to the user

In some cases, you need to allow some external sources to access your test system, like a partner or a customer, for some reason. These reasons cause others to have access to your sensitive information, and you may just want to allow access to some of the test environments. In this case, how do you provide a test system to the partner or customer to develop or test? The simplest is to provide a mock, whether it comes from your network or the customer's network. SoapUI mocks are very easy to configure and can be run in SoapUI or as a war package to your Java server.

Isolation system

Sometimes you want to test a separate part of the system without the impact of other parts of the system. Because other system parts will cause interference to the test data, it affects the test results based on data collection. Using mock you can remove the system-dependent simulations that need to be part of the test. When these mocks are isolated, the mocks becomes very simple and reliable, fast and predictable. This gives you a test environment that removes random behavior, has a repeating pattern, and can monitor a particular system.

Mockito Introduction

Mockito is a simple and popular Mock frame. It can help us create Mock objects and maintain the independence of unit tests.

Using it requires only adding dependencies in Maven.

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->    <dependency>        <groupId>org.mockito</groupId>        <artifactId>mockito-all</artifactId>        <version>2.0.2-beta</version>    </dependency>
Create a Mock object by method creation
class CreateMock {    @Before    publicvoidsetup() {        mockUserDao = mock(UserDao.class);          new UserServiceImpl();          userService.setUserDao(mockUserDao);      }}
Create with annotations
class CreateMock {    @Mock    UserDao mockUserDao;    @InjectMocks      private UserServiceImpl userService;      @Before      publicvoidsetUp() {          //初始化对象的注解         MockitoAnnotations.initMocks(this);      }  }
A simple example:
 PackageMockito;ImportOrg.junit.Assert;ImportOrg.junit.Test;ImportJava.util.List;Import Staticorg.mockito.mockito.*; Public  class MyTest {    @Test     Public void myTest() {/ * Create Mock Object * /List List = mock (list.class);/* Set expected to return "111" when calling the Get (0) method */When (List.get (0). Thenreturn ("111"); Assert.assertequals ("ASD",1,1);/ * Set to return expected results * /System.out.println (List.get (0));/ * Return NULL if not set * /System.out.println (List.get (1));/ * Invalid setting for Mock object * /List.add (" A"); List.add ("123");/ * Returns the result of the previous setting * /System.out.println (List.get (0));/ * Returns NULL * /System.out.println (List.get (1));/ * size is 0 * /System.out.println (List.size ());/* Verify operation, verify get (0) called 2 times */Verify (list, times (2). Get (0);/ * Verify the results are returned * /string ret = (string) list.get (0); Assert.assertequals (ret,"111"); }}

From the above code can see the general use of the steps:

The Setup method is expected to return

by When (List.get (0)). Thenreturn ("111") , set to return "111"when list.get (0) is called, the method is Stub, Replace our actual operation.

Validating method calls

This method validates the number of times that the get (0) method call is verify (list, times (2)). Get (0);You can also set whether to call, call time, and so on.

Verify the return value

assert.assertequals (ret, "111"); Method verifies that the return value after the Mock object method call is expected.

Mockito using Set Mock object expectation and return values
/* 表示第一次调用 someMethod() 返回 value1 第二次调用返回 value2 */when(mock.someMethod()).thenReturn(value1).thenReturn(value2);  when(mock.someMethod()).thenReturn(value1, value2);  /* 也可以设置两次 */when(mock.someMethod()).thenReturn(value1);when(mock.someMethod()).thenReturn(value2);

Another way of writing Doreturn ()

/* 表示第一次调用 someMethod() 返回 value1 第二次调用返回 value2 */doReturn(value1).doReturn(value2).when(mock).someMethod();  /* 若返回 void,则设置为 doNothing() */doNothing().when(mock).someMethod();
Returning an exception to a method setting
/* 当调用 someMethod() 方法时会抛出异常 */when(mock.someMethod()).thenThrow(new RuntimeException());/* 对 void 方法设定 */  doThrow(new RuntimeException()).when(mock).someMethod();  
Parameter matching device

We do not have to fix parameters such as get (0) when the Stub is called. Can be called by a parameter match.

when(list.get(anyInt())).thenReturn("hello");
Behavior Validation for Mock objects
 PackageMockito;ImportOrg.mockito.ArgumentCaptor;ImportOrg.mockito.InOrder;ImportOrg.testng.annotations.Test;ImportJava.util.List;Import Staticorg.mockito.mockito.*;/** * Created by ANDY.WWH on 2016/7/18. * * Public  class Behavior {    @Test     Public void Behaviorcheck() {List mock1 = mock (list.class); List Mock2 = mock (list.class);/ * Set expectations * /When (Mock1.get (0). Thenreturn ("Hello World"); When (Mock1.get (1). Thenreturn ("Hello World"); When (Mock2.get (0). Thenreturn ("Hello World"); Mock1.get (0);/ * Validate method call once * /Verify (MOCK1). Get (0); Mock1.get (0);/ * Verify method invocation two times * /Verify (Mock1, Times (2). Get (0);/ * Authentication method has never been called * /Verify (Mock2, never ()). Get (0);/ * Authentication method calls two times in 100 milliseconds * /Verify (Mock1, timeout ( -). Times (2). Get (Anyint ());/ * Set method invocation order * /Inorder inorder = inorder (Mock1, Mock2); Inorder.verify (Mock1, Times (2). Get (0); Inorder.verify (Mock2, Never ()). Get (1);/ * Query Whether there is a method called, but not validated by verify * /Verifynomoreinteractions (Mock1, Mock2);/ * Verify that the Mock object has not been delivered * /Verifyzerointeractions (Mock1, Mock2);/ * Parameter grabber * /argumentcaptor<integer> argumentcaptor = Argumentcaptor.forclass (Integer.class); Verify (Mock1, Times (2). Get (Argumentcaptor.capture ()); System.out.println ("argument:"+ Argumentcaptor.getvalue ()); }}
Verify the number of calls

Verify (Mock1, timeout. Times (2)). Get (Anyint ());

In addition to the methods in the code, Mockito also provides a
-Never () is not called, equivalent to The Times (0)
-AtLeast (n) is called at least n times
-Atleastonce () equivalent to atleast (1)
-Atmost (n) is called up to n times

Timeout validation

By timeout We can verify whether the program execution time conforms to the rules.

Method invocation Order

Inorder can verify the order of method calls

Verifynomoreinteractions and Verifyzerointeractions

Verifynomoreinteractions: Query whether there is a method that is called but not validated by verify

Verifyzerointeractions:verifyzerointeractions

Argumentcaptor parameter Grabber

You can capture the parameters of the method at validation time, and finally validate the captured parameter values. If a method has more than one parameter to capture validation, it is necessary to create multiple Argumentcaptor object processing.

Spy Object Verification

The Mock operation is all virtual objects. Even if we set the When (List.get (0)). Thenreturn (1), we call or 0 if the size () method is returned. Mockito also provides us with a way to manipulate real objects -theSpy

To make a simple comparison:

 PackageMockito;ImportOrg.testng.annotations.Test;ImportJava.util.List;Import StaticOrg.mockito.Mockito.mock;Import StaticOrg.mockito.Mockito.when;/** * Created by ANDY.WWH on 2016/7/18. * * Public  class mockobject {    @Test     Public void mocktest() {List List = mock (list.class); When (List.get (0). Thenreturn ("Hello World"); System.out.println (List.get (0));    System.out.println (List.size ()); }}

 PackageMockito;ImportOrg.testng.annotations.Test;ImportJava.util.LinkedList;ImportJava.util.List;Import StaticOrg.mockito.Mockito.spy;Import StaticOrg.mockito.Mockito.when;/** * Created by ANDY.WWH on 2016/7/18. * * Public  class mockobject {    @Test     Public void mocktest() {/ * Create real objects * /List List =NewLinkedList ();        List spy = Spy (list); Spy.add ("Hello"); When (Spy.get (0). Thenreturn ("Hello World"); System.out.println (Spy.get (0)); }}

See an example of the official website:

@Test   Public void spytest() {List List =NewLinkedList (); List spy = Spy (list);//Optionally, you can stub out some methods:When (Spy.size ()). Thenreturn ( -);//Using the Spy calls real methodsSpy.add ("One"); Spy.add ("both");//Prints "one"-the first element of a listSystem.out.println (Spy.get (0));//Size () method was stubbed-100 is printedSystem.out.println (Spy.size ());//Optionally, you can verifyVerify (Spy). Add ("One"); Verify (Spy). Add ("both"); }

Reference:

Preliminary study on Mockito

Mockito: A powerful simulation testing framework for Java development

Introduction to mock simulation test and Mockito use

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.