Jmockit Learning Notes (A, introduction)

Source: Internet
Author: User
Tags instance method

Jmockit Introduction

In the Jmockit Toolkit, the expectations &verifications APIs provide rich support for the creation of behavior-based unit tests. The focus of this test is on the interaction between the test unit and other associated test units. Test modules include Class,method and constructor.


The interaction between two cells usually manifests itself as a call between method or constructor.

A unit test usually only uses this unit that is tested. Some of the other units behind it need not be applied. Therefore, the purpose of unit testing is to test the internal logic of the unit, which should be isolated from the other units it relies on.

But we are not trying to isolate all of the dependent units in the test, and usually only isolate the following.

1 has (or is going to) own unit tests.

2) It is difficult to create or run in a test environment for some reason.

For these special units, we assume that these dependent behaviors are performed as expected (expectations).


mocked Types

The method or constructor that is called in the test cell, and the cells that are being relied upon are usually the objects that are emulated. Mocking provides a mechanism by which the units tested can be isolated from the units he relies on. We declare an object to be a mocked type to specify that the object in this test is simulated. The types that can be emulated are: Interface,class (including abstract and final type), annotation and enum.

By default, all methods in the modeled type are simulated. If a class is declared to be analog, all its parent classes until java.lang.Object (but not including java.lang.Object) are simulated. Therefore, the inherited methods are also automatically simulated. Other constructors in class are also modeled. Methods/constructors, whether private,static,final or native, can be simulated.

When a method or constructor is simulated, his original implementation code is not invoked during the test. The invocation of the method or constructor is jmockit in the redirect.


The following is one of the most basic examples.

@Test public
   void dobusinessoperationxyz ()
   {
      ...
      New Expectations () {//an ' expectation block '
         Dependency mockinstance;//' Dependency ' is we mocked type for this TE St ...
         {
            ...
            "Mockinstance" is a mocked instance automatically provided for use in the test
            mockinstance.mockedmethod (...);
            ...
         }
      };
      ...
   }

In general, the variables in the previous example can also be @mocked, @NonStrict, @Injectable these annotations to be declared to be simulated.


Expectations

A expectation is a set of calls to a particular impersonation method/constructor in a test. A expectation can contain different calls to the same method/constructor, but does not need to include all calls during the test. Whether a call can match a expectation not only determines the name of the method/constructor, but also depends on the parameters of the runtime, such as the instance of the object to which the method belongs, the value of the parameter, or the number of times it is invoked. Therefore, in expectation, you can specify some constraint conditions for matching calls.

We can also qualify the parameters of the invoked method in expectation to match a method call to a particular condition.

The following example is a expectation of the dependency#somemethod (int, String) method, and only a method call that satisfies the parameter value (1, "Test") will match to the expectation.

@Test public
   void dobusinessoperationxyz ()
   {
      ...

      New Expectations () {
         Dependency mockinstance;
         ...

         {
            ...
            An expectation for a instance method:
            Mockinstance.somemethod (1, "Test");
            ...
         }
      };

      A call to the ' unit under test occurs here, leading to mock invocations//' may or ' not
      match specified EXPE Ctations.
   }


The record-replay-verify model

All tests can be divided into at least three phases.

As shown below

@Test public
   void Sometestmethod ()
   {
      //1. Preparation:whatever is required before-under test can be exercised.
      ...
      2. The unit under test was exercised, usually by calling a.
      ...
      3. Verification:whatever needs to is checked to make sure the exercised unit
      //    did its job.
      ...
   }

The first is the preparation phase, in which the object or data that is required for testing is created or heavily acquired elsewhere.

The test unit is then executed.

Finally, the running result is compared with the expected value.

This three-stage model becomes also: Arrange, Act, assert syntax, ("AAA")

In tests that use mock types, we define the three phases as follows:

1 record phase: The call in this phase will be recorded. In the test preparation phase, before the test unit is run.

2 Replay phase: During this phase, the simulated call may be executed while the test unit is running. Calls to the impersonated method that were previously recorded are replayed. The recordings and playback that are normally invoked are not necessarily the relationships of the one by one mappings.

3 Verify phase: This phase can verify that the call is running as expected. In the test verification phase, the invoked method is run after execution.

behavior-based tests using Jmockit can be summed up in the following templates.

Import mockit.*;
   ... Other imports ... public class Sometest {//Zero or more "mock fields" common to all test methods in the class:
   @Mocked collaborator Mockcollaborator;
   @NonStrict anotherdependency anotherdependency; @Test public void testwithrecordandreplayonly (mock parameters) {//Preparation code not specific to J

      Mockit, if any.

         New Expectations () {//an ' expectation block '//Zero or more local mock fields.
            {//One or more invocations to mocked types, causing expectations to be recorded.
         Invocations to non-mocked types are also allowed anywhere inside this block.

      }
      };

      Unit under test is exercised.
   Verification Code (JUNIT/TESTNG asserts), if any. @Test public void testwithreplayandverifyonly (mock parameters) {//Preparation code not specific to JMo

      Ckit, if any.

      Unit under test is exercised. New Verifications () {//A ' Verification block '//one or more invocations to mocked types, causing expectations to be verified.
      Invocations to non-mocked types are also allowed anywhere inside this block.

      }};
   Additional Verification Code, if any, either this or before the verification block. @Test public void testwithbothrecordandverify (mock parameters) {//Preparation code not specific to JMo

      Ckit, if any.
         New Nonstrictexpectations () {//Also an expectation blocks//Zero or more mock fields.
         {//One or more invocations to mocked types, causing expectations to be recorded.

      }
      };

      Unit under test is exercised. New Verificationsinorder () {//also a verification block//one or more invocations to mocked types, causing ex
      Pectations to is verified//in the specified order.

      }}; Additional Verification Code, if any, either or before the verificationBlock.
 }
}


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.