Spring mvc: Test

Source: Internet
Author: User

The following packages are used:

Reference aopalliance-1.0.jar
Commons-collections.jar
Commons-dbcp.jar
Commons-logging-1.1.1.jar
Commons-pool.jar
Junit-4.4.jar
Jstl. jar
Log4j-1.2.15.jar
Mysql-connector-java-5.1.6-bin.jar
Spring-aop-2.5.6.jar
Spring-beans-2.5.6.jar
Spring-context-2.5.6.jar
Spring-context-support-2.5.6.jar
Spring-core-2.5.6.jar
Spring-jdbc-2.5.6.jar
Spring-tx-2.5.6.jar
Spring-test-2.5.6.jar
Spring-web-2.5.6.jar
Spring-webmvc-2.5.6.jar
Standard. jar

Mainly added two packages for testing, spring-test-2.5.6.jar and junit-4.4.jar!
Here, it should be particularly noted that since we use the annotation method will naturally use the JUnit-4.X series, and Sring-Test for JUnit has a tiring demand, JUnit version must be 4.4, high versions (such as 4.5 and 4.7) are not supported ). OtherwiseJava. lang. ClassNotFoundException: org. junit. Assume $ AssumptionViolatedExceptionException.
A parent class for testing that can be automatically rolled back -- AbstractTestCase
AbstractTestCase. java

Java code
  1. /**
  2. * 2009-12-16
  3. */
  4. PackageOrg. zlex. spring;
  5. ImportOrg. junit. runner. RunWith;
  6. ImportOrg. springframework. Test. abstracttransactionalperformancespringcontexttests;
  7. ImportOrg. springframework. Test. Context. contextconfiguration;
  8. ImportOrg. springframework. Test. Context. junit4.springjunit4classrunner;
  9. ImportOrg. springframework. Test. Context. transaction. transactionconfiguration;
  10. ImportOrg. springframework. transaction. annotation. Transactional;
  11. /**
  12. * @ Author <a href = "mailto: zlex.dongliang@gmail.com"> liangdong </a>
  13. * @ Version 1.0
  14. * @ Since 1.0
  15. */
  16. @ Contextconfiguration (locations = "classpath: applicationcontext. xml ")
  17. @ Runwith (springjunit4classrunner.Class)
  18. @ Transactional
  19. @ TransactionConfiguration (transactionManager = "transactionManager", defaultRollback =True)
  20. Public Abstract ClassAbstractTestCaseExtends
  21. AbstractTransactionalDataSourceSpringContextTests {
  22. }
/*** 12-12-16 */package org. zlex. spring; import org. junit. runner. runWith; import org. springframework. test. abstractTransactionalDataSourceSpringContextTests; import org. springframework. test. context. contextConfiguration; import org. springframework. test. context. junit4.SpringJUnit4ClassRunner; import org. springframework. test. context. transaction. transactionConfiguration; import org. springframework. transaction. annotation. transactional;/*** @ author <a href = "mailto: zlex.dongliang@gmail.com "> Liang Dong </a> * @ version 1.0 * @ since 1.0 */@ ContextConfiguration (locations =" classpath: applicationContext. xml ") @ RunWith (SpringJUnit4ClassRunner. class) @ Transactional @ TransactionConfiguration (transactionManager = "transactionManager", defaultRollback = true) public abstract class extends acttestcase extendsimplements acttransactionaldatasourcespringcontexttests {}

It is troublesome to write a bunch of configurations for each test class! Simply come to the old man to complete the basic work for Son, son, and sun!
Line-by-line analysis:
@ ContextConfiguration (locations = "classpath: applicationContext. xml ")Import the configuration file. At this time, we can see the advantages of using the applicationContext. xml file as the system control file! Of course, this configuration of Spring-Test only recognizes classpath, so I have to copy these files to the root directory!
@ RunWith (SpringJUnit4ClassRunner. class)SpringJUnit support, which introduces Spring-Test framework support!
@ TransactionalThis is critical. If you do not add this annotation configuration, the transaction control will be completely invalid!
@ TransactionConfiguration (transactionManager = "transactionManager", defaultRollback = true)Here the transaction is associated with the transaction controller (transactionManager = "transactionManager") in the configuration file, and the automatic rollback (defaultRollback = true) is specified ). This operation will not pollute the database!
AbstractTransactionalDataSourceSpringContextTestsTo build this series of pollution-free pure green transaction testing frameworks, you must find this base class!
The following figure shows the overall structure:

Files in the "test" subdirectory will be compiled to the classpath Directory, which is also a maven test project! Copying a bunch of configuration files is indeed inconvenient!
AbstractTestCase. java is used to abstract test class control.
AccountDaoTest. java is used for the AccountDao test.
DaoAllTests. java is used for the overall test of the Dao layer.
Let's take a look at AccountDaoTest.
AccountDaoTest. java

Java code
  1. /**
  2. * 2009-12-
  3. */
  4. PackageOrg. zlex. Spring;
  5. ImportJava. util. date;
  6. ImportOrg. JUnit. test;
  7. ImportOrg. springframework. Beans. Factory. annotation. autowired;
  8. ImportOrg. zlex. Spring. Dao. accountdao;
  9. ImportOrg. zlex. Spring. domain. Account;
  10. /**
  11. * @ Author <a href = "mailto: zlex.dongliang@gmail.com"> liangdong </a>
  12. * @ Version 1.0
  13. * @ Since 1.0
  14. */
  15. Public ClassAccountdaotestExtendsAbstracttestcase {
  16. @ Autowired
  17. PrivateAccountDao accountDao;
  18. @ Test
  19. Public VoidTest (){
  20. Account ac =NewAccount ();
  21. Ac. setBirthday (NewDate ());
  22. Ac. setUsername ("SPRING ");
  23. Ac. setPassword ("SNOWOLF ");
  24. Ac. setEmail ("spring@zlex.org ");
  25. // Create a user
  26. AccountDao. create (ac );
  27. // Search
  28. Account account = accountDao. read ("SPRING ");
  29. // Verification
  30. AssertNotNull (account );
  31. }
  32. }
/*** 12-12-16 */package org. zlex. spring; import java. util. date; import org. junit. test; import org. springframework. beans. factory. annotation. autowired; import org. zlex. spring. dao. accountDao; import org. zlex. spring. domain. account;/*** @ author <a href = "mailto: zlex.dongliang@gmail.com "> Liang Dong </a> * @ version 1.0 * @ since 1.0 */public class AccountDaoTest extends AbstractTestCase {@ Autowiredprivate AccountDao accountDao; @ Testpublic void test () {Account ac = new Account (); ac. setBirthday (new Date (); ac. setUsername ("SPRING"); ac. setPassword ("SNOWOLF"); ac. setEmail ("spring@zlex.org"); // create user accountDao. create (ac); // retrieve Account account = accountDao. read ("SPRING"); // verify assertNotNull (account );}}

Remember to use annotations@ TestThe identification method is enough!
A piece of data is inserted here and then retrieved. If the data exists, the test is successful! Of course, at this time, you should check whether a piece of data is inserted in the database!
Execute this method, monitor the database at the same time, observe the log! The most effective way is to add a breakpoint when executing the search method and monitor database records. You will find that this data entry is unavailable in the database at this time! In fact, this is an uncommitted transaction!
Complete the operation and check the logs at this time:

The database has actually been rolled back!
Let's take a look at DaoAllTests.
DaoAllTests. java

Java code
  1. /**
  2. * 2009-12-17
  3. */
  4. PackageOrg. zlex. spring;
  5. ImportOrg. junit. runner. RunWith;
  6. ImportOrg. junit. runners. Suite;
  7. ImportOrg. junit. runners. Suite. SuiteClasses;
  8. /**
  9. * @ Author <a href = "mailto: zlex.dongliang@gmail.com"> liangdong </a>
  10. * @ Version 1.0
  11. * @ Since 1.0
  12. */
  13. @ RunWith (Suite.Class)
  14. @ SuiteClasses ({AccountDaoTest.Class, AccountDaoTest.Class})
  15. Public ClassDaoAllTests {
  16. }
/*** 12-12-17 */package org. zlex. spring; import org. junit. runner. runWith; import org. junit. runners. suite; import org. junit. runners. suite. suiteClasses;/*** @ author <a href = "mailto: zlex.dongliang@gmail.com"> liangdong </a> * @ version 1.0 * @ since 1.0 */@ RunWith (Suite. class) @ SuiteClasses ({AccountDaoTest. class, AccountDaoTest. class}) public class DaoAllTests {}

Line by line description:
@ RunWith (Suite. class)Set Test
@ SuiteClasses ({AccountDaoTest. class })Set, including the AccountDaoTest class. Multiple test classes can be separated by commas!
This test class can be used to test the Dao layer set and is irrelevant to Spring!

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.