Mockito a great simulation framework for Java development __java

Source: Internet
Author: User
Tags stub soapui
Original address: Https://www.codeproject.com/articles/516360/mockito-a-great-mock-framework-for-java-developmen

Mockito is a satirical frame that tastes very good. It allows you to write beautiful tests using a clean and simple API. introduce

This art will show some basic concepts of the mock framework, why we should use it, and deduce a simple way to apply Mockito in Java.
the concept of a Mock

Outside the world of software development, the term "mock" means imitation or impersonation. Thus, "mocks" can be thought of as a stand-alone, fake, or, most commonly, software development, a kind of a.

Fakes are often used as dependencies for the test class.

Terms and definitions
Dependencies -dependencies refer to a category in an application that relies on another class to perform its intended function. A dependency is usually stored in an instance variable in a dependency class.
subjects-during unit testing, the term "unit" usually refers to a separate class, especially the test write class. Therefore, the tested class is the application class that is being tested.
why simulate.

When we learn to program, our objects are usually self-contained. Any good world is not dependent on external classes (System.out), nor does it write many other classes in the process of learning a language. However, in the real world, software has dependencies. We have operations classes that depend on the services and services of the data Access object (DAO), and the list continues.

The idea of unit testing is that we want to test our code without testing dependencies. This test allows you to verify that the code you are testing is working, regardless of whether it is dependent or not. The theory is that if I write code that works according to design, my dependencies work according to design, then they should work together according to the design. The following code will be an example: Hide Copy code

import java.util.ArrayList;
public class Counter {
     public Counter() {
     }
     public int count(ArrayList items) {
          int results = 0;
          for(Object curItem : items) {
               results ++;
          }
          return results;
     }
} 

I know the example above is as simple as what you've got, but it illustrates a point. If you want to test the method count, you will write in the test to resolve how the Count method works. You are not trying to test how ArrayList works because you assume it has been tested and designed to work. Your only goal is to test your use of ArrayList.

The idea behind the mock object is that we want to create an object that replaces the real object. This mock object will expect to invoke some method with some parameters, and in this case it will return an expected result. What is the key to the mock concept.

When it comes to mocks, you need to worry about just 3 things. Kill, set expectations and validate. Some unit test scenarios do not involve any of these situations, while other individual test scenarios involve only the pile rods, while others involve setting expectations and validation. stub

Stubbing is a fake process that tells you how to behave when it interacts with it. You can usually store public properties (public properties with getter and/or setter) and public functions.

When it comes to stubbing features, you usually have a lot of options. You may want to return a specific value, throw an error, or schedule an event. In addition, you may want to indicate how the function behaves depending on how it is invoked (that is, by matching the type or value of the parameter passed to the function).

If this sounds like a lot of work, it can be, but it's generally not. A big feature of many mock frameworks is that you don't need stub void functions. You also do not have to store any functions that are not invoked or properties that are not queried during the execution of the test. Set Expectations

One of the main features of counterfeiting is the ability to tell the fake test runtime's expectations. For example, you might want to call a particular function 3 times. You may expect it to never be invoked. You may want it to be called at least two times, but not more than 5 times. You might want to invoke a particular type of parameter or a specific value or any of these combinations. The possibilities are endless.

Setting expectations is the process of telling you what is going to happen to you. Remember, because it's fake, it doesn't actually happen. However, the class you are testing is not smart. From its point of view, it calls this function and expects it to do anything it should do.

For what is worthwhile, most mock frames allow you to create an interface or a common class of impersonation. You are not limited to simulating interfaces only. Validate

Setting expectations and validation coexist. Set expectations before calling the function of the test class. Validation completed. So, first you set expectations and then verify that your expectations are met.

From the point of view of the unit test, if your expectations are not met, the unit test fails. For example, if you set the Iloginservice.login function with the expectation that a particular username and password should be invoked once, but it is not invoked during the execution of the test, the forgery is not validated and the test fails. what is the benefit of a Mock .

You can create tests in advance; TDD

This one is one of the more powerful benefits. If you create an emulator, you can write service tests before the service is created, enabling you to add tests to the automation environment during development. In other words, service mocking allows you to use test-driven development.

teams can work in parallel

This creates a test similar to the above code that does not exist. But the previous point was to write tests for the developers, which is for the Test team. How the team starts to create tests when you don't have any tests. Simulate it, and test the emulator. This means that when the service is ready for testing, the QA team can actually prepare a complete set of tests; We don't have downtime when one team waits for another to finish. This makes mockery of the financial argument particularly strong.

You can create proof of concept or presentation.

Because mocks can be cost-effective, you can use mocks to create proof of concept, line framework, or as a demo of the application you are considering building. This is very powerful, to decide whether to continue to develop the project, but the most important thing is to provide a good foundation for the actual design decision.

you can write test resources that are not accessible

This is one of the benefits that falls outside the category of actual interest, but as a lifeguard. Once you wanted to test or use a service, you were told that the service was behind a firewall, that the firewall could not be opened for you, or that you were authorized to use the firewall. When you do this, a mockservice is placed in an accessible location, including on your local computer, and is a life-saving person.

The simulator can be delivered to the customer

In some cases, you cannot allow access to test systems of external sources, such as partners or customers. These can be the result of access security, information sensitivity, or just the fact that the test environment may not be 24/7 accessible. In these cases, you can provide a test system for your partner or customer to start development or testing. A simple solution is to provide a simulation from your network or your customer's own network. SOAPUI simulation is very easy to deploy, it can be run in Soapui, also can be used as. The war file is exported and placed in the Java server of your choice.

you can isolate the system

Sometimes you want to test part of the system without affecting other system parts. This is because other systems add noise to the test data, making it more difficult to draw better conclusions from the collected data. With mocks, you can remove all systems and scoff at all systems, except for a system you need to determine in your tests. These taunts can be made very simple but reliable, fast, and predictable when it comes to mocking isolation. This gives you a test environment in which you have removed all random behaviors, have repeatable patterns, and can monitor a particular system well. Mockito Framework

Mockito is a Java Open source testing framework released under MIT licenses.
Mockito distinguishes the other mocking framework by allowing developers to predetermine the behavior of the system being tested (SUT). [4] One of the criticisms of mock objects is the tight coupling between the test code and the system being tested. [5] The coupling is reduced or minimized because Mockito attempts to eliminate the expected run verification mode [6] by eliminating the expected specification. The result of this distinguishing feature is simpler test code that should be easier to read and modify. You can verify the interaction: Hide Copy Code

// mock creation
List mockedList = mock(List.class);
// using mock object
mockedList.add("one");
mockedList.clear();
// selective and explicit vertification
verify(mockedList).add("one");
verify(mockedList).clear();   
or Stub method callsHide Copy Code
// you can mock concrete class, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
// stubbing - before execution
when(mockedList.get(0)).thenReturn("first");
// following prints "first"
System.out.println(mockedList.get(0));
// following prints "null" because get(999) was not stubbed.
System.out.println(mockedList.get(999)); 
Simple sample Java code with Mockito


No mock frame


Using the Mockito framework Step 1: Create a MAVEN project in Eclipse

The definition pom.xml is as follows: Hide Shrink Copy Code

<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0"           xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"           xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd /maven-4.0.0.xsd ">   <modelVersion>4.0.0</modelVersion>   <groupId> vn.com.phatbeo.ut.mockito.demo</groupid>   <artifactId>demoMockito</artifactId>   < version>0.0.1-snapshot</version>   <packaging>jar</packaging>   <name> demomockito</name>   <url>http://maven.apache.org</url>   <properties>      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>   </ properties>   <build>     <sourceDirectory>src</sourceDirectory>      <testsourcedirectory>test</testsourcedirectory>     <plugins>        <plugin>       

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.