First discussion

zhaozj2021-02-16  68

JUnit's framework and application special discussion

Open Source Technology Topics> Thoughts

Poplar finishing Foxcrane released

Lecture Outline:

0. Background introduction

1. How to use JUnit (instance)

2. The main and methods of junit (theory)

3. JMOCK's extended and use method for JUnit (instance, theory)

4. Strutsjunit Test example for Struts (instance)

5. Exemption and probably understanding of existing test tools (theory)

6. PMD Test for static code (instance)

7. Testing questions to pay attention to (theory)

0. Background introduction

For a long time, the software developers I have been in contact have rarely test work in the process of development. Most of the projects are written in test documents when final acceptance. Some items do not even test documents. Now there is a change. We have been advocating UML, RUP, software engineering, CMM, with only one, improve the quality of software preparation. So these mortals - Only at the same time can only focus on a number of points (according to scientific statistics, the general people can only consider up to 7 or so, the master can reach 12), not only to overview global Refers to Details - I can only expect other ways to ensure the quality of the software we have written. Test is a good way to ensure software quality.

First: The purpose of the test is simple and attractive, it is to write high quality software.

Second: Test is a continuous process. That is to say, during the entire process of testing and development, the unit test is particularly suitable for the development process of iterative incremental type (iTERATIVE AND INCREMENTAL)

Third: You should not write the program before you don't know how to test the code. Once you have completed the program, the test code should also be completed. Unless the test is successful, you can't think that you have written out how you work.

Test First Design, which is respected in XP is based on the above technology. If you want to write a code, you need:

Write test with JUnit, then write code

Write code, run test, test failure

Modify the code, run the test until the test is successful

TEAM development under Java, generally adopting CVS (version control) Ant (project management) JUnit mode:

Go to work every morning, each developer gets a copy of the entire project from CVS Server.

Get your own task, first write the test code for today's task.

Then write the code of today's task, run the test until the test passes, the task is completed

One or two hours before get off work, each developer submitted the task to CVS Server

Then run automatic testing throughout the project, which test is wrong, find the relevant personnel to modify until all tests are passed. Go to get off work. . .

From this we can see the needs of JUnit.

1. How to use JUnit [Reference: How to use JUnit Framework to write unit testing]

JUnit is a unit test framework, the framework is its focus. Everyone first looks at the code:

Package HibernateTest;

Import junit.framework.test;

Import junit.framework.testsuite;

Public class testALL {// Defines a Suite, which can be considered similar to the Java application for JUnit.

Public static test suite {

/ / Define two TestSuite

Testsuite Suite = New Testsuite ("Root Hibernate Tests");

Testsuite Childsuite = New Testsuite ("Child Hibernate Tests");

// Composition a test directory tree

Suite.addtest (childsuite);

Childsuite.addteSuite (Testsample.class);

Childsuite.addteSuite (Testsample.class);

System.out.println ("Test data quantity:" suite.counttestcases);

Return suite;

}

}

This is the main program I use to test Hibernate's test case management. Don't worry, I haven't arrived at test code J, let's talk about the test framework, which is the reason why it becomes a test frame rather than a test tool. Its results are shown below:

We can see a test tree structure in the figure. This code can say the following points:

Define a Suite that declares that the role of JUnit can be considered similar to the Java application.

Public Static Test Suite {......}

And the directory of this directory tree is shown in the following code:

/ / Define two TestSuite

Testsuite Suite = New Testsuite ("Root Hibernate Tests");

Testsuite Childsuite = New Testsuite ("Child Hibernate Tests");

The organization and nodes of the catalog are shown in the following code:

Suite.addtest (childsuite);

Childsuite.addteSuite (Testsample.class);

Childsuite.addteSuite (Testsample.class);

Just said that the management of the test catalog tree is now ready to say the writing, that is, the test code:

Package HibernateTest;

Import junit.framework.testcase;

Import junit.framework.test;

Public Class Testsample Extends Testcase {

Public void testmethod1 {

Try {

Boolean b = true;

Asserttrue ("Error prompts this information", b);

} Catch (exception e) {

System.out.println ("Error prompts this information");

}

}

}

Note the following code:

Public Class Testsample Extends Testcase

Extends TestCase is a key part. In this way, it becomes a test function.

Look at the next key part of the code:

Public void testmethod1 {...}

Testxxx is also a test method.

At this time, please review the second chart at the beginning, that is, the test catalog, check, the impact of the critical part of these codes on the tree directory structure.

2. Main and method of junit

First, in the test framework, see how this test is completed: a) Testcase.run calls TestResult.run

b) TestResult.run calls TestResult .startTest

c) TestResult.run creates an Anonymous class to implement the interface portECTABLE

d) Testcase .Runbare calls Testcase .Runbare in the Portectable. protect method

e) Call the Runbare by running portectable.runbare, add an error via Exception

Explain as follows:

First, a test is started, but it will not call the test code directly. If so, then it is not a test frame. J. TestResult is a class of record results, and if it calls the test code directly, it will issue problems. The problem is that when multiple tests are in the same time, what should I do after a test error? [Currently B]

Next, it is Portectable appearance: [Currently C]

PUBLIC Abstract void protect () throws throwable;

By this definition can ensure that any error and exception will be thrown if any error and Exception are running without causing the program to continue running. This is also the work of C. After these preparations are finished, you can call the test code.

After these preparations are completed, TestCase .Runbare in D is a truthful call test code.

Finally, the increasing error is recorded through the Exception capture to the testResult, and it can be output in text or graphics.

In this process, there are some classes and methods that are invited to be as follows:

a) Method Throws is the ancestors of all Error and Exception, which can be thrown when any error and exception are running through this definition, and will not cause the program to continue to run.

b) TestResult is used to run and collect test results (capture via Exception).

c) The use of the TestListener interface is the same as its name for listening. Mainly used for runtime listeners, Baserunner (all run classes, such as Testrunner) implements this interface. Since it is implemented by TestResult, you can add monitoring as long as TestResult.AddListener is called.

d) Assert Assert Assess is whether there is two failures in the JUnit you need, and there are two failures in junit. If it is thrown in the program being tested, it also believes that the test failed.

3. JMOCK's extension and usage method for JUnit [Reference: Using JMOCK Auxiliary Unit Test]

JMOCK is an extension to JUnit and is a test framework based on JUnit. JUnit When the unit test is completed, some functions are implemented, or there is trouble, such as repeating multiple times, and the parameters cannot be added in JUnit, making dynamic interactions also become a problem. The emergence of JMOCK makes the test use more convenient, and a large number reduces the writing of test code.

The example is as follows:

MockStmt.Expect (ONCE) .Method ("Execute"). with (EQ (SQL)). Will (ReturnValue (false);

Explain as follows:

EXPECT: Looking forward to the number of executions, there can be onCE, Atleastonce, Notcalled three Method: the method name of the expected call

WITH: Parameters required

Will: Return Value

The ONCE, EQ, RETURNVALUE is a method inheriting from the MockObjectTestCase.

After execution, Green, success. Try twice

Assertfalse (stmt.execute (sql));

Then prompt the error.

Related knowledge of the MockObject.

4. Strutsjunit Test example of Struts

Strtustest is an extension of JUnit. It is easy to test the Struts application (container external test) without starting a servlet container. It also belongs to the use of the Mock object test, but it is different from Easymock that Easymock is an API that provides a Mock object, and StrutStest is dedicated to test the MOCK object test framework for testing the Struts application. In addition to the container test, StrutStest can also be very convenient to test the test in the container. Please see the example:

Public class deparmentdbactiontest extends mockstrutstestcase {

Public DeparmentdbActionTest (String arg0) {

Super (arg0);

}

Public void setup () {

Super.setup ();

/ / Indicate the root of the web application

File contextfile = new file ("D: // projects // fog // impLement // Web");

SetContextDirectory (contextfile);

}

protected void teardown () throws exception {

Super.teardown ();

}

Public void testdoadd () {

// Set the Action's path

SetRequestPathInfo ("[(!)] edit");

// Prepare the parameters of the FormBean required for Action

AddRequestParameter ("Method", "DoAdd");

AddRequestParameter ("PageID", "1");

AddRequestParameter ("DPNAME", "Test Department");

AddRequestParameter ("DPTYPE", "Test Department");

AddRequestParameter ("YN", "N");

// Execute an action

ActionPerform ();

// Verify the return forward

VerifyForward ("Success");

}

}

For details, you can continue to study, today is mainly wide and short.

5. Exemption and probably understanding of existing test tools

What we just introduced is a test for dynamically running results, and for static code is also a test tool. Here are just a introduction, interested everyone can go to see:

Findbugs

PMD / CPD

Checkstyle

Jalopy / Jacobe

Jdepend

Junit

Findbugs: Mainly solved current and latent faults, using bytecode analysis to generate his fault report. Among them, the word code analysis is the key.

PMD: Use source code analysis, similar to the compiler work mode, allowing you to use the XPath engine to access the output parser of the source code. Source code analysis is the key. Checkstyle: quite similar to PMD, as shown in the name, it is mainly to find format faults. The format fault is key.

Jalopy / Jacobe: Helps the code format program that helps to resolve the accident waiting for a fault and organizational failure. Jalopy is open source, but he did not appear in active development. Jacobe can be used free of charge, but not open source.

JDepend: There are countless measures around your source code, including coupling and distribution from the incoming and outgoing of the main sequence.

6. PMD Test of static code

For static code testing, I recommend it is PMD because I use this J. Please see the example below:

Public Class Testsample Extends Testcase {

Public void testmethod1 () {

Try {

INT i = 0;

Boolean b = true;

Asserttrue ("success", b);

} Catch (exception e) {

System.out.println ("Yes, i catch u"); // should arrive at point

}

}

}

Please judge that those code is wrong? They are all small issues.

1) INT i = 0 is useless, you can delete

2) Testsample, class name should be capitalized

You now think PMD, is it like a program master J. 7. Test questions should be paid attention to

Discussion in the group [微雨 心]

Testing this thing is very strange, everyone is doing, but good and bad differences are too big. The test driver is high, mainly: the boundary of the test, the test can be repeated (that is, the next rewriting parameters will be tested this time). Often, can't grasp (experience) on the boundary issue, so that the coverage of the test is low (effectiveness coverage, not the method). In addition, the mutual interference and reuse problems of test parameters are introduced, and the auxiliary classes established for data cleaning and to facilitate testing. Moreover, the general experience is not rich, it is not easy to see a problem or confident, so it is natural to feel no problem. Alternatively, it is also possible to use testing and original classes to test. There is also the use of the top and the underlying on the top and the bottom layer. Because, although I like and insist on testing, I also have time problems, and these issues are too confident to me. The test is "top", which is the user's angle to check the class / method, then the implementation is the bottom. Usually, this "bottom" may be multi-layered, and in some cases, I may not test priority. At this time, it is very good to walk and test each other. For example, I originally developed my BRAVE, I am alone, for time progress, I will come. Of course, I am confident that it will ignore the test or suspense. This approach is more practical together on both sides. J

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

New Post(0)