Mock Object tool lateral comparison (on)

zhaozj2021-02-17  99

Foreword

This article:

1. Compare only the dynamic MOCK tools and tools that automatically generate Mock Object implementation

2, compare only the limited tools listed in the article

3, comparison of use only, no technical comparison

It can be seen as a entry manual using the Mock Object Assisted Unit test.

sequence

In the practice or theory of current popular software development, unit testing (UT, UNIT TEST) has been widely accepted as "best practices" developed by software. JUnit is an unlatable king in the unit test tool.

When we test simple objects or algorithms, it is very simple to write JUnit-based unit tests. When we are ready to test a class or algorithm that relies on other objects, an example of these collaborators is needed. At this time, the writing of test cases is slightly complicated. Furthermore, when we prepare a web system or complex business unit test, the work of constructing a "partner" instance may be inefficient and expensive.

For example: Testing an object using an HttPRequest instance, you need to start the web server, construct the Request instance and fill in the required value, and stop the web server after the test is finished. In this way, the construction of the test data and the environment may be very complicated, and it will be difficult to reach the "automatic test" target.

Mock Object

At this point, Mock Object gives us a solution: Mock Object has an interface with the "partner" "partner" of the subject, and is passed to the subject as "partner"; when the subject calls cooperation When Mock Object changes certain states or returns the desired result according to the testor's will to check if the measured procedure works in accordance with the desired logic to achieve the purpose of the unit test.

figure 1

figure 2

Alternatively, Mock Object acts as an "emulator" in unit test cases, "spoof" and tracking of the subject. As long as the behavior of Mock Object is consistent with the subject's expectations, it will not have any impact on the subject.

When we write unit test cases with Mock Object, the code style usually this:

1. Create: Create an instance of Mock Object

2. Training: Set the status and expectations in Mock Object

3. Test: Tune the Mock Object as a parameter to call the subject

4. Verify: Verify the consistency in Mock Object and the return value or status of the subject object

Step 2 We are usually called the training of Mock Object. At this point, we need to "tell" Mock Object to be tested which interfaces are called, what is the order of calls, what is the react? In step 4, Mock Object will check if the subject is called in the previous training, and whether the order of the adjounted interface, the order of calls, and the number of call times are correct. If the correct words are OK, otherwise, indicating that the subject does not implement the desired function.

From the above description, we can see that Mock Objects

1. You can simulate the object being simulated, build a virtual test environment;

2. Can you set what interfaces will be called and perform the desired action at that time;

3. You can verify that the subject is called in the Mock Object in accordance with the set rules.

Mock Object Generate Tool

At the beginning, Mock Object is completely written by the tester. In this way, it is unavoidable to write test case efficiency, low and test cases, and may even affect the passion of the XP practitioner "test first". At this point, a variety of tools that help create Mock Object will be delivered.

In these tools, there are mockobjects, xdoclets, and other tools to write Mock Object implementations, and Easymock, MockCreators, and so on automatically create tools for Mock Object instances / classes. This article is only description for the latter. In these tools that automatically create Mock Object instances / classes, it is divided into two: a similar to Easymock, they can dynamically create Mock Object instances; a mockcreator, they can generate static Mock Object code. The most famous and currently maintaining the following tools: MockObjects, Easymock, Mockcreator. Below, we will use these tools to write unit test code below, and compare the same as the use of the use:

Package mocktest;

Import java.io. *;

Import javax.servlet. *;

Import javax.servlet.http. *;

public

Class SimpleCalcServlet

Extends httpservlet

{

public

Void Doget (httpservletRequest request, httpservletResponse response)

Throws ServleTexception, IOException

{

Integer a = integer.decode (Request.GetParameter ("a"));

Integer B = Integer.Decode (Request.GetParameter ("B"));

Int results = a.intValue () b.intValue ();

Response.setContentType (Text / HTML ");

PrintWriter out = response.getwriter ();

Out.print ("Result =" result);

Out.flush ();

}

}

This class is a servlet, we can use the JUnit to extend: httpUnit to write its test case. However, how to use HTTPUNIT is not the content discussed herein.

If you use Mock Object to write unit test cases for this class, the essence is how to construct an instance of HTTPSERVLETREQUEST and HTTPSERVLETRESPONSE. Below, we will show it to how to use the tools mentioned above to solve this problem:

MockObjects

We have four ways to use MockObjects to write test cases:

1. Framework based on MOCKOBJECTS, write your own Mock Object implementation and share it with others;

2, test directly using Mock Objects provided by MockObjects;

3. Use the DYNAMOCK module included to quickly obtain the Mock Object instance;

4. Help us quickly build a test environment through the Helpers object it provides.

However, this article only focuses on how to use Dynamock to write test cases

[1]:

1.

public

Void testsimpleadditionusingdyNamock ()

Throws servletexception, ioException {

2.

Final Mock MockhttpServletRequest =

NEW MOCK (httpservletRequest.

Class);

3.

Final Mock MockhttpServletResponse =

New Orderedmock (httpservletResponse.class,

4. "Response with Non-Default Name");

5.

6. MockhtpServletRequest.expectandReturn ("getParameter", "B", "4");

7. MockhtpservletRequest.expectandReturn ("getParameter", "A", "3");

8.

9.

Final StringWriter Output =

New stringwriter ();

10.

Final PrintWriter ContentWriter =

New PrintWriter (OUTPUT);

11.

12. MockhtpServletResponse.expect ("setContentType", "text / html");

13. MockhtpservletResponse.expectandReturn ("GetWriter", ContentWriter;

14.

15. SimpleCalcServlet ASERVLET =

NEW SimpleCalcServlet ();

16. ASERVLET.DOGET (httpservletRequest) mockhtpservletRequest.Proxy (),

17. (httpservletResponse) MockHttpservletResponse.Proxy ());

18.

19. mockhtpservletRequest.verify ();

20. mockhtpservletResponse.verify ();

21. Assertequals ("Output Should Be An Addition", "Result = 7", Output.toString ());

twenty two. }

"Code Style", LINE2 ~ 4, "Create" Mock Object: "Create" Mock Object instance:

● We used two different classes to construct Mock Object: one is MOCK, one is OrderedMock. The same difference between them is in the order in which the interface is called, a sequence that needs to detect the interface called.

LINE6 ~ 13 is "training" Mock Object:

● When training Mock Object, we call its ExpectAndReturn () method. This method has multiple overloads. For test methods Chapter 6, it expresses the meaning of the test code to invoke the parameter "b" to call the getparameter () method of MockHttpservletRequest; when the message is received, MockhttpServletRequest will return a string "4" .

LINE15 ~ 17 is "test":

● When the test is actually tested, pass the Mock Object instance to the measured code by calling the Proxy () method of the MOCK class instance.

LINE19 ~ 21 is "Verification":

● At this time, consistency verification is performed using the Verify () method of the MOCK class instance.

[1]

In order to save space, simply, this article only lists the code of the Test method in the JUnit test case.

转载请注明原文地址:https://www.9cbs.com/read-31538.html

New Post(0)