Jmockit Study Notes (1. Introduction)

Source: Internet
Author: User
Introduction to jmockit

In the jmockit toolkit, expectations & verifications APIs provides abundant support for the creation of behavior-based unit tests. This test focuses on the interaction between the test unit and other associated test units. The test unit includes class, method, and constructor.

The interaction between two units is usually a call between method or constructor.

A unit test usually only uses this unit to be tested. Some other units on which it depends do not need to be used. Therefore, the purpose of a unit test is to test the internal operation logic of the Unit, and the test should be isolated from other units on which it depends.

However, during testing, we do not need to isolate all the dependent units. We usually only isolate the following situations.

1) You have (or will) your own unit tests.

2) For some reason, it is difficult to create or run in the test environment.

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

Mocked types

The methods or constructor called in the test unit and the dependent units are usually simulated objects. Mocking provides a mechanism to isolate tested units from their dependent units. We declare an object of the mocked type to specify that the dependent object in this test is simulated. The following types can be simulated: interface, class (including abstract and final types), annotation, and enum.

By default, all methods of the simulated type are simulated. If a class is declared as simulated, all its parent classes until java. Lang. Object (but does not contain java. Lang. Object) are simulated. Therefore, the inherited methods are automatically simulated. In addition, constructors in the class are also simulated. Whether it isprivate,static,finalOrnativeMethods/constructor can be simulated.

When a method or constructor is simulated, its original implementation code will not be called during the test. The call to this method or constructor will be redirected to jmockit.

The following is a basic example.

@Test   public void doBusinessOperationXyz()   {      ...      new Expectations() { // an "expectation block"         Dependency mockInstance; // "Dependency" is our mocked type for this test         ...         {            ...            // "mockInstance" is a mocked instance automatically provided for use in the test            mockInstance.mockedMethod(...);            ...         }      };      ...   }

Normally, variables in the above example can also be passed through@Mocked,@NonStrict,@InjectableThese annotations are simulated for declaration.

Expectations

An expectation is a group of calls to a specific simulated method/constructor in the test. An expectation can contain different calls to the same method/constructor, but it does not need to be included in all calls during the test. Whether a call can match an expectation not only determines the name of the method/constructor, but also the runtime parameters, such as the instance and parameter value of the object to which the method belongs, or the number of calls. Therefore, in expectation, you can specify some constraints that match the call.

We can also limit the parameters of the called method in expectation to match the method call with specific conditions.

In the following exampleDependency#someMethod(int, String)MethodExpectation: expectation is matched only when the method call that satisfies the value of this parameter (1, "test.

@Test   public void doBusinessOperationXyz()   {      ...      new Expectations() {         Dependency mockInstance;         ...         {            ...            // An expectation for an instance method:            mockInstance.someMethod(1, "test");            ...         }      };      // A call to the unit under test occurs here, leading to mock invocations      // that may or may not match specified expectations.   }
The Record-replay-verifyModel

All tests can be divided into at least three stages.

As shown below

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

The first step is the preparation phase. The objects or data required for testing in this phase will be obtained by creating or re-reading other places.

Then the test unit is executed.

Finally, compare the running result with the expected value.

 

This three-stage model also becomes the arrange, act, and assert syntax ("AAA" for short ")

In a test using a simulated type, we define the three phases as follows:

1) record stage: calls in this phase will be recorded. In the test preparation phase, the task is performed before the unit is run.

2) replay stage: During this stage, the simulated call may be executed when the test unit is running. The call to the simulated method previously recorded will be played back. Normally, the called recording and playback do not necessarily have a one-to-one ing relationship.

3) verify stage: this stage can verify whether the call runs as expected. In the test and verification phase, the called method is run after execution.

The behavior-based tests conducted using jmockit can be summarized into 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 JMockit, 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 JMockit, 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 here or before the verification block.   }   @Test   public void testWithBothRecordAndVerify(mock parameters)   {      // Preparation code not specific to JMockit, if any.      new NonStrictExpectations() { // also an expectation block         // 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 expectations to be verified         // in the specified order.      }};      // Additional verification code, if any, either here or before the verification block.   }}

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.