Build a JUnit test package with Jython

Source: Internet
Author: User
Tags run python script
Build a JUnit test package with Jython

Python and Java work together to accomplish impossible tasks

Document options



the required JavaScript document options are not displayed

send this page as an email


Level: elementary

Michael nadel, mnadel@flywheelcorporation.com, Java developer, Chicago technology partners

May 01, 2004

Developers can choose to automate unit tests for multiple reasons. Many people even further exploit it to automate the positioning and execution of these tests. But what if I want to test the device module (testharness) to run as defined statically? Follow the developer Michael nadel to see how to use python to simulate static-defined JUnitTestsuiteClass.

The JUnit testing framework is used by more and more development teams. Thanks to a variety of Test Modules, you can now test any Java applicationProgramAlmost every component. In fact, almost the entire secondary market seems to be built around JUnit. Modules including cactus, jfcunit, xmlunit, dbunit, and httpunit can be used for testing applications for free. As the complexity of the system increases and so many tools are available, there is no reason not to rely on unit testing.

No, developers are not just programmers. We interact with users to fix bugs and determine requirements. We attended the meeting and made a telemarketing call. We have completed some (sometimes all) quality assurance functions. Since there are so many responsibilities, it is natural to want to be as automated as possible. Because good teams (except for other things) perform a lot of tests, people who want to automate different development processes often perform detailed research on this field.

Automated Unit Testing

There are many ways to automate the positioning and execution of all project test cases. One solution is to use ant togetherJUnitTask and embeddedFilesetTask. In this way, you can include and exclude files in a specific directory (based on the file name style ). Another option is to use eclipse, which can specify the directory where all tests are located and executed. The previous option provides the flexibility to filter running tests (and because it is a pure headless Java application that can run in almost all places ), the latter option allows debugging of the "dynamic" package. Can the two methods be combined with the power and flexibility?

With PythonProgramming LanguageJava platform implementation-Jython, the answer is loud "Yes !" (If you are not familiar with Jython, you should add this knowledge before continuing this article. For more information, see references below ). With the strength and elegance of Jython, you can maintain a file system, search for Classes matching certain styles, and dynamically compile JUnit.TestsuiteClass script. ThisTestsuiteSimilar to all other static-defined classes, you can easily debug with your favorite debugging program. (The example used in this article assumes that Eclipse IDE is used. However, the technology I described here can be used in most other ides without many modifications .)

When making any design decision, you must weigh the impact of the selection and decision. Here, in order to obtain the ability to debug dynamically generated test packages, additional complexity must be added. However, this complexity is mitigated by Jython itself: Jython has been well tested and well supported, and is openSource code. Moreover, python is increasingly becoming the de facto standard for object-oriented and platform-independent programming. For these two reasons, there is little risk of using Jython, especially it provides the following benefits: dynamically generated JUnit in creation and debuggingTestsuiteClass has unparalleled flexibility.

If Jython is used or not, it can be used to solve the problem. If Jython is not used, you can use a Java property file to store a group of classes, directories, and packages to add or exclude tests in the packages. However, if you select Jython, you can use the entire Python language and runtime to solve the problem of which tests you choose to execute. Python scripts are much more flexible than Java property files, and they are limited by your imagination.

Using the seamless integration of Jython and the Java platform, you can create static definitions, but dynamically build them.TestsuiteClass. There are a lot of tutorials on JUnit, but let's take a look at the following two lines.CodeAs a review. Listing 1 is a static buildTestsuiteClass (this example is taken fromJUnit: A Cook's tour,For links to it and other JUnit resources, see references ):

Listing 1. statically defining testsuite

Public Static Test Suite (){
Return new testsuite (moneytest. Class );
}

Listing 1 indicatesTestsuiteYesbyTestClass instance. This assembly module fully utilizes this point. To analyze the code of this tool, you should download the sample jar file in this article from references. This document contains two files: dynamictestsuite. Java and getalltests. py. The former is dynamically generated using a phthon script.TestsuiteJUnit test fixture module, which is a Python script for searching for files matching a specific style. Dynamictestsuite. Java built with getalltests. pyTestsuite. You can modify getalltests. py to better suit the needs of your project.



Back to Top

Understand the testing Module

How does the Code work? First, assign getalltests. py to obtain a groupTestClass. Then, use the Jython API to extract the list from the python runtime environment. Then, use the Java reflection API to constructTestIn the list of class namesStringClass instance of the object. Finally, use the JUnit APITestAddTestsuite. The cooperation between the four databases can achieve your goal: to dynamically buildTestsuiteIt can run as static definitions.

Take a look at the JUnit suite list in Listing 2. It is a publicPublic static testsuite Suite ()Method SignatureTestcase. ByJUnitFramework callSuite ()Method callGettestsuite (),Gettestsuite ()Also calledGetclassnamesviajython ()To obtain a groupStringObject, each of which representsTestcaseClass.

Listing 2. dynamically defining testsuite

/**
* @ Return testsuite a test suite containing all our tests (as found by Python script)
*/
Private testsuite gettestsuite (){
Testsuite suite = new testsuite ();
// Get iterator to class names we're re going to add to our suite
Iterator testclassnames = getclassnamesviajython (). iterator ();
While (testclassnames. hasnext ()){
String classname = testclassnames. Next (). tostring ();
Try {
// Construct a class object given the test case class name
Class testclass = Class. forname (classname );
// Add to our suite
Suite. addtestsuite (testclass );
System. Out. println ("added:" + classname );
}
Catch (classnotfoundexception e ){
Stringbuffer warning = new stringbuffer ();
Warning. append ("Warning: Class '"). append (classname). append ("' Not found .");
System. Out. println (warning. tostring ());
}
}
Return suite;
}

Make sure that the system attributes are correctly set at the beginning. Internally, Jython will usePython. HomeAttribute to locate the desired file. Will eventually callGetclassnamesviajython ()Method, there will be some wonderful things happening here, as will be seen in listing 3.

Listing 3. Extracting Java objects from Python Runtime

/**
* Get list of tests we're going to add to our suite
* @ Return list a list of string objects, each representing class name of a testcase
*/
Private list getclassnamesviajython (){
// Run Python script
Interpreter.exe cfile (getpathtoscript ());
// Extract out Python object named python_object_name
Pyobject alltestsaspythonobject = interpreter. Get (python_object_name );
// Convert the python object to a string []
String [] alltests = (string []) alltestsaspythonobject. _ tojava _ (string []. Class );
// Add all elements of array to a list
List testlist = new arraylist ();
Testlist. addall (arrays. aslist (alltests ));
Return testlist;
}

First, judge the python file. Then, extractPyobject. This is the expected object. It contains the class names of all test cases that will constitute the test package (remember --PyobjectIs the Java runtime counterpart of the python object ). Then create a specificListAndPyobjectFill it_ Tojava __InstructionsPyobjectConvert the content into a JavaStringArray. Finally, the returnedGettestsuite (), Load the test cases of the Jython logo here and add them to the composite.



Back to Top

Install the test fixture module in the Development Environment

Now I have a good understanding of how to test the assembly module and may not be able to try it on my own. You need to complete the following steps to configure eclipse to run this installation module. (If you use different ides, you should be able to easily modify these steps for your environment .)

    1. Install Jython 2.1. If not. (For more information, see references ).

    2. Copy getalltests. py to the main directory.
    3. Edit getalltests. py row 25th to specify the root path of the source file. The file name that matches * text. Java in the org package in all directories under this location will be searched.
    • If necessary, modify row 54th to change the root package name (for example, change to com ).

  • Copy dynamictestsuite. Java to the source tree.
  • Add the following jar to the Eclipse project:
      • JUnit. Jar (the binary file of the JUnit framework. For download information, see the JUnit web site ).
      • Jython. Jar (the Jython binary file, located in the Jython installation directory ).
  • SetDynamictestsuiteClass is loaded into the eclipse Java source file editor. Perform one of the following steps:
      • SelectDynamictestsuite, Or
      • PressCTRL + Shift + TEnter the choose type fieldDynamictestsuite.
  • SelectRunAnd then selectDebug....
  • SelectJUnitConfiguration.
  • ClickNewButton. A new JUnit target will be created,DynamictestsuiteThe test class field should be prefilled.
  • SelectArgumentsTab.
  • In the VM parameter text box, type-Dpython. Home = <path where you installed Jython>.
  • ClickDebugButton.
  • Change! Now we have a specific JUnitTestcaseClass, which can be processed like a static defined package. Set borders and perform debugging! No need to modifyTestClass, the device module will build a package, just as you explicitlyClassThe same is true for writing objects to packages. To perform a test, you can call this module through your favorite debugger, compilation tool (such as ant or cruisecontrol), or test runner in JUnit.

    Expand this device module
    I believe that unless you modify the source code before running, this module can only be used for one project. This module can be easily expanded to support multiple projects. One simple way is to modifyGetpathtoscript ()To use System Properties specified for project-specific properties. You can use it freely in your own project. You can use it without changing it, or perform processing based on it. However, do not forget its GPL license.

    References

    • For more information, see the original article on the developerworks global site.

    • Download the source code used in this article.
    • If you are new to Jython, do not miss Barry Feigenbaum's comprehensive "Jython Introduction "(Developerworks, January 1, April 2004 ).
    • Visit the Jython homepage to obtain binary files, source code, and documents.
    • For more information about JUnit and unit testing, see JUnit web site.
    • JUnit: A Cook's tourThis article provides an in-depth introduction to JUnit.
    • In ant of Matt Chapman's comprehensive introduction to "Apache ant 101: make Java builds a snap" (December 2003), he introduced the steps involved in compiling a simple Java project's compilation file, other useful functions of ant are analyzed, including file system operations and style matching. InArticleFinally, you need to write your own Java class that extends ant's functions.
    • DeveloperworksArticles and tutorials on general information about JUnit and unit testing, including:
      • "Using Ant and JUnit for incremental development" Malcolm Davis (November 2000)
      • "Is testing an interesting thing? Really ?" Jeff canna (March 2001)
      • "Unit tests on ejbs using JUnit in visualage for Java" Sultan Ahamed Kaja and Sunil mahamuni (December 2002)
      • "Unit tests with simulated objects" Alexander day chaffee and William pietri (November 2002)
      • "Integrate JUnit plug-ins into WebSphere Studio" Sunil mahamuni and pagadala J. Suresh (August 1, March 2003)
    • Eric AllenDeveloperworksPrevious topicDiagnose Java codeWe often discuss how unit tests help with software development. Go to the documents in this topic to find out more.
    • Eclipse is an open-source development platform.
    • In "debugging with the eclipse platform "(Developerworks, September May 2003) read the Pawel Leszek's how-to article.
    • Ant is a good way to create flexible and portable compiling scripts.
    • WebSphere version 4 Application Development Handbook contains a section on automated unit testing in JUnit.
    • Visit developer bookstore to obtain a detailed list of technical books, including hundreds of Java-related books.
    • You can also get a complete list of free Java-related tutorials from the home page of the Java technology area on developerworks.

     

    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.