Unit Test notes 2nd in spring

Source: Internet
Author: User

Author: Jiangnan Baiyi

Effective TDD can indeed speed up, rather than slowing down the development progress (the one-sided pursuit of comprehensive unittest coverage is not listed here)
1. Real hierarchical development can be achieved.
2. No dependency or frequent restart of Web container.
3. Manual testing can hardly help changing the database. It is a headache to restore the database to its pre-test status. Unit test can use the automatic rollback mechanism to cleverly solve this problem.

Unit Test in spring focuses on three aspects:
1. Bean dependency Injection
2. Transaction Control, open session in test and default rollback
3. Test the control layer without webiner iner

1. Bean dependency Injection
It has always been spring's pride to establish applicationcontext and inject pojo dependencies without relying on webiner iner.

String [] paths = {"classpath: applicationcontext *. xml "};
Applicationcontext CTX = new classpathxmlapplicationcontext (paths );
Userdao Dao = (userdao) CTX. getbean ("userdao ");

If you're in trouble with this, as long as your testcase inherits from the Spring-mock.jarAbstractdependencyinjectionspringcontexttestsTo implement the Public String [] getconfiglocations () function, and explicitly write some setter functions of the variables to be injected.
Note: because it is autowire, the variable name must be the bean ID in the spring context file.

2. Open Session in test and automatic rollback
It's also something from spring's magic country. You can let testcase inherit from abstracttransactionaldatasourcespringcontexttests, and you can achieve open session in test to solve the lazy-load problem of hibernate; the transaction control definition in the original Dao is taken over. The setdefaultrollback (Boolean) method is used to control the final rollback or commit. If the default value is rollback, data changes generated during the test will not affect the data in the database.
 
If you cannot inherit from this base class, you can simply write the code as follows:

Protected platformtransactionmanager transactionmanager;
Protected transactionstatus;
Protected Boolean defaultrollback = true;
Public void setup ()
{
Transactionmanager = (platformtransactionmanager) CTX. getbean ("transactionmanager ");
Transactionstatus = transactionmanager. gettransaction (New defaulttransactiondefinition ());
}
Public void teardown ()
{
If (defaultrollback)
Transactionmanager. rollback (this. transactionstatus );
Else
Transactionmanager. Commit (this. transactionstatus );
}

(Note: Hibernate is too fraudulent. If all the data is rolled back by default, it will only work in the session and will not write the database at all, and the test results will not be fully achieved .)

BTW. abstracttransactionaldatasourcespringcontexttests also creates a jdbctemplate object through the injected datasource. You can run SQL to check the hibernate results, but pay attention to the transactions between the two.

3. unit test at the Controller Layer

On the Controller layer, mockhttpservletrequest and response provided by spring are used to simulate the real servlet environment. In spring 2.0, A abstractmodelandviewtests is added to provide some utils functions for detecting returned values.

Protected xmlwebapplicationcontext CTX;
Protected mockhttpservletrequest request = new mockhttpservletrequest ("get ","");
Protected mockhttpservletresponse response = new mockhttpservletresponse ();
Protected controller = NULL;
Protected modelandview mv = NULL;
Public void setup ()
{
String [] paths = {"Maid *. xml", "myappfuse-servlet.xml "};
CTX = new xmlwebapplicationcontext ();
CTX. setconfiglocations (paths );
CTX. setservletcontext (New mockservletcontext (""); CTX. Refresh ();
Controller = (customercontroller) CTX. getbean ("customercontroller ");
// Add the preceding transaction control code
}
Public void testcustomerlist () throws exception
{
Request. setrequesturi ("/customer. Do ");
Request. addparameter ("action", "listview ");
MV = controller. handlerequest (request, response );
Assertmodelattributeavailable (mV, "MERs ");
}


4. Further simplified
The names of these two base classes are too long.
Second, there are some definitions of common context files.

So I can abstract a few more.Base class,They are daotestcase and controllertestcase.

5. easymock
Mockobject is a good thing for thoroughly layered development, and it is easy to use. And there is no longer a restriction that only interfaces are supported and class is not supported.

// Set bookmanager mockobject
Bookmanagermockcontrol = mockclasscontrol. createcontrol (bookmanager. Class );
Bookmanagermock = (bookmanager) bookmanagermockcontrol. getmock ();
Controller. setbookmanager (bookmanagermock );

// Record the expected values of the getallbook () and getcategorys Methods
Bookmanagermock. getallbook ();
Bookmanagermockcontrol. setreturnvalue (New arraylist ());
Bookmanagermockcontrol. Replay ();

// Perform the operation
MV = controller. handlerequest (request, response );
// Verification Result
Assertmodelattributeavailable (mV, "books ");

Easy mock vs jmock:

Jmock requires that testcase inherit from mockobjecttestcase. This hinders the inheritance system that I inherited from modelandviewtestcase of spring2.0 and mockdao and realdao. Therefore, easymock is not so domineering.

In addition, although easymock's script recording is not as elegant as jmock, it is better than short and easy to read. The jmock sentence is too long.

6. Display Layer Test
In addition, the display layer does not have any good unittest method, whether it is an immature httpunit or a bulky GUI test tool. Appfuse always uses the thoughtwork selenium and j3unit, which claim to support prototype.

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.