Jmock Quick Start Tutorial

Source: Internet
Author: User
Tags compact

Original: http://blog.sina.com.cn/s/blog_6b30a46b01013lgf.html Overall RatingMock testing is a common method of testing. Often when testing is performed, the test code often needs to interact with some real objects, or the execution of the code being tested depends on the functionality of the real object. At this point, we can use a lightweight, controllable mock object to replace the real object, simulating the behavior and function of the real object, so as to facilitate our testing. JMock is an implementation of this approach. JMock is a lightweight test tool that uses mock objects to test Java code. No exception, it is part of the Xunit family, as it evolved from JUnit and is an enhanced library of JUnit. JMock is easy to use and easy to master. With it, we can easily and quickly construct the desired mock object, which makes it easy and quick to write unit test code, which is very suitable for the smooth development of test driven. Features and featuresWith Jmock, we don't have to stop writing the test code as we used to, instead of writing a special mock object. Furthermore, JMock allows you to precisely define the constraints that interact with each other in a very flexible way to better simulate and characterize the invocation relationship between objects. The constrained expression of this kind of jMock between objects is very concise and compact, which
It makes the test code writing very concise, but also can make good use of mock object to achieve the test intent. In addition, JMock is easy to expand and we can easily add custom requirements. JMock can be well integrated and used together with other existing test frameworks, such as JUnit. Background IntroductionAn introduction to the project development team is available on the official website of Jmock. There are currently 5 developers with commit permissions, namely: Steve Freeman, Timmackinnon, Nat Pryce, Mauro Talevi, and Joewalnes. It is worth mentioning that these developers are almost all from the agile practice of ThoughtWorks. Among them, Steve Freeman and Nat Pryce participated in the ACCU Conference, held in Oxford, UK, in April 2006, and gave a keynote address on the evolution of Jmock APIs, as well as in the Java and C # fields, embedded DSL (domain-specific language Language). Stevefreeman, one of the major developers of the Jmock project, is an independent consultant in Agile Software Development, and an early promoter of extreme programming practice in the UK region. He co-authored a paper, "Mock Roles, not Objects", with 3 other jmock authors besides Mauro Talevi, and explored the experience of mock testing techniques. This paper was included in the Oospa Proceedings of 2004, where the electronic version of the paper can be found on the official homepage of Jmock. In addition to Jmock, several developers have developed Jmock's C # implementation version--nmock. In addition to developers, there are contributors to jmock projects that provide advice, patches, and documentation for the project. However, Jmock's online documentation resources are not very rich, fortunately Jmock's code is simple and sophisticated, so interested readers may want to drill down into the code to find out. References website ClassHttp://www.jmock.org/jMock's official website. Here you can find the latest downloads for Jmock, learn about Jmock's latest news, and related documentation resources to show you how to write test code with Jmock, how to master constraints, and how to compare them with similar mock test tools. Http://www.easymock.org/EasyMock's official website. This is a mock test framework with similar functionality to Jmock. has now been updated to version 2.3, starting with version 2.2.2, Easymock supports impersonation of the class in addition to supporting simulation of the interface. An example of a message publishing and subscribing systemHere, we use a simple example to demonstrate how jmock is used by the reader. This is a simplified message publishing and subscription system example, is a typical observer model, familiar with the design pattern of readers will not be unfamiliar. We use Publisher to represent the message sender, and we use subscriber to represent the message subscribers (that is, the receiver). The following is the definition of the Subscriber interface:
Interface Subscriber {
void receive (String message);
}
A publisher can send a message (here expressed as a string object of string type) to a specific implementation class of 0 or more subscriber. The specific implementation class of Subscriber is registered with the interface provided by publisher. In this example, we are designed to test publisher's execution logic without caring for the implementation logic of the specific subscriber. To do this, we need to construct a mock object to simulate the behavior of subscriber. Then register it in Publisher. First, we have to introduce Jmock's related packages and construct a mockery object. This object is a unified portal for Jmock to provide mock capabilities, which we will use to simulate the behavior of subscriber, and use it to verify the correctness of Publisher's invocation of subscriber's mock object.
Import org.jmock.Expectations;
Class Publishertest extends TestCase {
Mockery context = new mockery ();
...
}
Now, let's write the test method, which is a test scenario where publisher sends a message to one of the Subscriber instances registered with it.
public void Testonesubscriberreceivesamessage () {
...
}
We first use the mockery instance to construct a simulated subscriber object, construct a Publisher object, and register the Subscriber, and then we define a message to be published.
Final Subscriber subscriber = Context.mock (subscriber.
Class);
Publisher publisher = new publisher ();
Publisher.add (subscriber);
Final String message = "message";
Next, we use mockery to define "expectations" for the simulated subscriber object--specifying the interaction rules between Publisher and Subscriber. The expectations here is a concept of the Jmock framework. In short, expectations is a set of constraint rules that define how we expect mock objects to accept calls during a test run. For example, in this case, we expect Publisher to call Subscriber's Receive method once, and the Receive method will receive a string type of message object. Please refer to the following article for a detailed description of the expectations.
Context.checking (new Expectations () {{
One (subscriber). Receive (message);
}});
Expectations is a major feature of Jmock, and it is distinguished from other mock testing tools. JMock offers a full range of flexible, concise and compact expectations, which are also expressed in close proximity to natural language. The construction of the entire mock object is done using the definition of a one or two-line expectations. This is a typical application of a built-in DSL, according to JMock authors, JMock's expectations is a DSL for mock testing in this particular area. Next, we start calling publisher's execution logic and validating the result after the call:
Publisher.publish (message);
Context.assertissatisfied ();
Here, we use the mockery instance again to verify that Publisher's call to Subscriber executes as expected. If the call is not as expected, the test will fail. The following is the complete sample code:
Import Org.jmock.Mockery;
Import org.jmock.Expectations;
Class Publishertest extends TestCase {
Mockery context = new mockery ();
public void Testonesubscriberreceivesamessage () {
Set up
Final Subscriber subscriber = context.
Mock (Subscriber.class);
Publisher publisher = new publisher ();
Publisher.add (subscriber);
Final String message = "message";
Expectations
Context.checking (new Expectations () {{
One (subscriber). Receive (message);
}});
Execute
Publisher.publish (message);
Verify
Context.assertissatisfied ();
}
}
From the above example, we can summarize the general process of using Jmock for mock testing, and use pseudo-code to organize the following:
... Create Mockery Object ...
public void Testsomeaction () {
... Some set up work ...
Context.checking (new Expectations () {{
... Define expectations here ...
}});
... Call the measured logic ...
Context.assertissatisfied ();
... Perform other assertions ...
}

Expectations usage Profile Jmock's expectations has the following structure:
Invocation-count (Mock-object). Method (Argumentconstraints);
Insequence (Sequence-name);
When (State-machine.is (state-name));
would (action);
Then (state-machine.is (New-state-name));
The Mock-object is a pre-constructed mock object, such as the subscriber of the preceding example, while the method is the name of the methods of the mock object that is about to be accepted, such as the Receive method for the preceding subscriber interface. Except for Invocation-count and Mock-object, subsequent content is optional. You can also append multiple insequence, when, will, and then clauses to a expectation, depending on your actual needs. Invocation-countRepresents the desired number of method calls, JMock provides several means of expressing the number of method calls, as shown in table 18-1: Table 18-1 JMock The representation of the number of method calls provided
Argument-constraints represents a constraint on a method call passed in a parameter, which can be an exact match, as shown in the following example, the Calculator Add method expects only two integer 1 as the parameter:
One (Calculator). Add (1, 1);
You can also use the WITH clause to define a fuzzy match condition, which is also the calculator Add method, which in the following example expects to accept arguments of any int type:
Allowing (Calculator). Add (with (Int.class)),
With (any (int.class)));
In addition to any, JMock also provides a variety of other forms of parameter constraint clauses, as shown in table 18-2: Table 18-2 jMock the parameter constraint clauses provided wouldA constraint that represents the return of a method call, JMock provides a return constraint as shown in table 18-3: Table 18-3 JMock provides a return constraint
insequenceUsed to define the order in which multiple method calls are executed, the insequence clause can define multiple, the order in which it appears in the test code, and the order in which the method calls are executed. To define a new order, you first need to define a sequence object, as follows:
Final Sequence sequence-name = context.sequence ("Sequencename");
Then, to define the order in which the method calls are executed, you can add a insequence clause after each expectation that is written sequentially. As shown below:
One (turtle). Forward (10); Insequence (Drawing);
One (turtle). Turn (45); Insequence (Drawing);
One (turtle). Forward (10); Insequence (Drawing);
When and then is used to define a method to invoke execution only when certain conditions are true, thereby further constraining the invocation of a mock object. In Jmock, this constraint is achieved in the form of a state machine. First, we need to define a state machine instance where the initial state (initial-state) is optional:
Final states State-machine-name =
Context.states ("State-machine-name"). Startsas ("Initialstate");
Then, we can use the When clause to define when a method is called to execute when it is in a state, and then to define the migration of the state when a method is called to execute. Examples are as follows:
Final states pen = context.states ("pen"). Startsas ("Up");
One (turtle). Pendown (); Then (the pen.is ("Down"));
One (turtle). Forward (10); When (Pen.is ("Down"));
One (turtle). Turn (90); When (Pen.is ("Down"));
One (turtle). Forward (10); When (Pen.is ("Down"));
One (turtle). Penup (); Then (the pen.is ("Up"));
The official website from Jmock can be downloaded to the current version. At present, its latest version is released in August 2007 in 2.4. Version 0. This release introduced support for JUnit 4.4 and made a number of minor improvements. JMock since the release of the 1.2.0 version in 2006, its API composition has changed significantly, and thus the use of JMock has also had an impact. Currently, there are 22 versions of Jmock 1 and Jmock on the official website of Jmock, respectively, and two copies of the respective documents. It can be considered that JMock 1 and JMock 2 are two parallel independent branches. Perhaps this is a bit confusing for developers who used to write mock tests using the Jmock 1 series version. However, since it is two parallel independent branches, and has now entered the "Stable" stage, for jmock old users, there is no need to worry about the Jmock version upgrade caused by the code incompatibility problem, because we can still use Jmock 1, without having to deliberately upgrade to Jmock 2. Of course, if it's a newly launched project, then using Jmock 2 would be a better choice. Community PerspectiveThe use of JMock can provide a great convenience for the unit test writing based on the mock technique, so that we can quickly write the mock object and then isolate the object under test. In fact, in the field of mock testing, there are a lot of good mock test framework, such as often by people and Jmock Easymock, excellent open source software spring used Easymock, and spring itself provides a set of convenient mock objects, These mock objects are published with spring's release package. JMock is not absolutely superior to other similar software, each mock test framework has its own characteristics, there are advantages and disadvantages.      here, the author picks Jmock as the main reason to introduce the object, it is the unique way in the construction of mock object. Simple and close to natural language expression forms, is an interesting application of DSL technology, but also makes mock object construction process is simple and accurate. In addition, in the past when people use jmock 1, they often complain that Jmock requires testcase to inherit from Mockobjecttestcase. This is taboo in the Java language, which is characterized by a single inheritance, because it prevents the test case from inheriting other parent classes. However, as we have seen from the above example, JMock 2 has made improvements in this area and no longer has a special parental restriction on testcase, which should be said to be a great improvement. In addition, the use of mock technology needs to have an accurate grasp, too many mock objects may also cause problems arise. When an object needs to construct too many mock objects before testing, the code logic that constructs the mock object in the test code occupies the majority of the space, which often means that there is a design problem with the code being tested. The introduction of mock testing tools like Jmock makes it easy to construct mock objects, which often encourages the spread of bad smell in code: Even if there is excessive coupling in the code, it seems that everything can easily depend on a mock. There is no silver bullet, the design flaw is simple mock technology can not solve, nor it should be solved, this belongs to the misuse of technology.      Finally, it's important to point out that while Jmock provides a lot of expressions to constrain mock object method calls, most of the time we just need to use a small portion of them. Too many constraints on the Mock object method invocation means that you need to have more dependencies and awareness of the other objects on which the code is being tested, and that once the object being relied upon is refactored, it is oftenCauses the failure of the associated test case. Sometimes, repairing these failed test cases is often a tedious task, which is a major hurdle to the smooth practice of TDD and refactoring.

(GO) jmock Quick Start Tutorial

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.