[Struts] Introduction to unit test on action using strutstestcase

Source: Internet
Author: User

Currently, test-driven development is becoming more and more popular. Because there is a reasonable existence, this development method must have its advantages. As a smallProgramPersonnel, the pursuit of new technologies is an important motivation for work. I believe everyone will share the same feeling.

Test-driven development is an important part of extreme programming (XP). It can be seen from the literal that it is tested first and thenCode. This may seem a bit strange. In fact, you can regard test cases as requirements. The programmer's job is to write code that meets such requirements, that is, to make these tests pass. As there is no actual code before writing a test case, the test result will not pass. As the Code increases, more and more tests are passed and all tests are finally passed. At this time, we can basically say that every functional unit of the system is correct, and the rest of the work is integration testing. The mission of these test cases is not over. Because the code is constantly modified, we need to run tests frequently (for example, every day) to check whether the current code can pass tests. Obviously, this test is completely automated, which ensures quality quickly.

Every action in a system using struts components can be considered as a function unit, which forms the main body of the system. (Of course, not all of your business logic must be directly written in the Action execute method, but this method will call these logics in a certain way .) Strutstestcase (http://strutstestcase.sourceforge.net/) is a packaging of JUnit, which provides a very convenient way to test these actions. It provides two testing methods: Mock (Simulated Object) and cactus (Real Environment). Currently, I only tested the former and found that the results are very good.

I have already written some code, so what I do is not really a test "driver" development. I mainly use strutstestcase as an automated test tool, to ensure the quality of the Code.

For example, I have an action class named saveteacheraction, its module name is teacher, the access path is/save, and it is associated with the actionform named teacherform (struts-config-teacher.xml) the configuration is as follows:

< Action
Attribute = " Teacherform "
Input = " /Form/teacher. jsp "
Name = " Teacherform "
Path = " /Save "
Scope = " Request "
Type = " Edu. PKU. CC. democenter. Teacher. Action. saveteacheraction " >
< Forward name = " Success " Path = " /List. Do " Redirect = " True "   />
</ Action >

The execute method in the saveteacheraction class is as follows. hibernatedao is the packaging class I wrote for persistent operations. beauutils is a utility in the Jakarta commons package, you can copy between the same attributes of two bean objects:

Public actionforward execute (
Actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response)
Throws exception {

Hibernatedao Dao = Hibernatedao. getinstance (getservlet (). getservletcontext ());
Teacherform = (Teacherform) form;
Teacher t = Null ;

If ( " Create " . Equals (teacherform. getaction ())){
T = New Teacher ();
}
If ( " Edit " . Equals (teacherform. getaction ())){
T = (Teacher) Dao. findbycode (teacher. Class, teacherform. getcode ());
}

Beanutils. copyproperties (T, teacherform );

Dao. saveorupdate (t );
Return Mapping. findforward ( " Success " );
}

Next, I will write a test case to test this action. Using strutstestcase in eclipse is very simple. You only need to include the strutstest-2.1.2.jar package and the JUnit package in the classpath of the project to start writing. I name this class testsaveteacheraction, that is, add the "test" text before the action class name. The package is also separated from the actual code and edu is used. PKU. cc. democenter. name of test (in comparison, the package name of saveteacheraction is edu. PKU. cc. democenter. teacher. action, democenter is the name of our project ).

Now let's take a look at the content of testsaveteacheraction:

Package edu. PKU. CC. democenter. test;

Import servletunit. Struts. mockstrutstestcase;
Import edu. PKU. CC. democenter. Teacher. Form. teacherform;

Public class testteacheraction extends mockstrutstestcase {

Protected Void Setup () throws exception {
Super. Setup ();
Setconfigfile ( " Teacher " , " /WEB-INF/struts-config-teacher.xml " );
}

Protected Void Teardown () throws exception {
Super. teardown ();
}

Public Void Testsaveteacheraction_create (){
Setrequestpathinfo ( " /Teacher " , " /Save " );
Teacherform form = Makeform ();
Form. setaction ( " Create " );
Form. setcode ( " Test. Create " );
Setactionform (form );
Actionperform ();
Verifyforward ( " Success " );
}

Public Void Testsaveteacheraction_edit (){
Setrequestpathinfo ( " /Teacher " , " /Save " );
Teacherform form = Makeform ();
Form. setaction ( " Create " );
Form. setcode ( " Test. Edit " );
Setactionform (form );
Actionperform ();

Form. setaction ( " Edit " );
Form. setbirthdate ( " 1979-1-10 " );
Setactionform (form );
Actionperform ();
Verifyforward ( " Success " );
}

Private teacherform makeform (){
Teacherform form = New Teacherform ();
Form. setaction ( " Create " );
Form. setbirthdate ( " 1979-1-1 " );
Form. setcode ( " Test.001 " );
Form. setemail ( " Test@test.com " );
Form. setname ( " Test " );
Form. setshortname ( " CS " );
Form. settel ( " 62760000 " );
Return Form;
}
}

All test cases using mock inherit from the class servletunit. Struts. mockstrutstestcase. The setup and teardown methods are the places for preparation and aftercare before and after testing. All the testing methods to be run start with test. The system automatically calls these methods.

Because saveteacheraction has two running modes based on the action parameters in the request: Create and edit, I wrote two test methods to test them respectively. Note that the sequence of running these test methods is uncertain. Do not think that you can run the create test first, and then edit the object just created on this basis, check the testsaveteacheraction_edit method.

I specified the module and the corresponding configuration file name in the setup method. If there is no module, skip this step. In the actual testsaveteacheraction_create method, first use the setrequestpathinfo method to specify the path and module of the action to be tested. If there is no module, you can use a method with the same name as a parameter. Then construct an actionform. For my example, teacherform. to simplify the code, I wrote a makeform method to generate a teacherform with filled values. Use setactionform to connect the teacherform to the action. The actionperform method notifies the execution of the action. In this case, the action will forward the request to a forward named success. Therefore, we use the verifyforward ("success") method to verify whether the request is forwarded. If this step fails, the unit test fails. Otherwise, the unit test is successful.

The testsaveteacheraction_edit method is similar to the testsaveteacheraction_edit method. You only need to create and modify the object in this method, but you cannot use the object created in the testsaveteacheraction_create method because the execution sequence of the two methods is unknown.

It is easy to run this test in eclipse. Double-click the class and select Run as-> JUnit test from the run menu. You will see a JUnit view, there is a green progress bar in it. If you go to the header and keep green, it means all tests are successful. Otherwise, it turns red and the stack information of the exception is displayed below. (Sense of accomplishment)

Now, I have made a very simple introduction to strutstestcase today. I have just started using it and will certainly encounter problems in the future. Please stay tuned for future reports.

In additionArticleIt can be found on the Internet. It is good to get started, for example:

Http://plateau.sicool.com/article/tdd/strutstestcast_junit_tdd.htm

In my opinion, it is best to first find a document when encountering a problem. After getting used to it, we will not only solve the problem quickly, but also learn more about it while reading the document.

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.