Talk about unit tests (iii)--spring test+junit perfect combination

Source: Internet
Author: User
Tags java web

In the "programmers who don't write unit tests are not good programmers" principle, I'm sticking with the unit test, not saying that all Java Web applications are based on spring, but at least more than half are Spring-based. After discovering bean management through spring, there are a variety of shortcomings in testing, for example, when many people do unit tests, They also initialize the spring container in the before method, causing the container to be initialized multiple Times. [java]View PlainCopyprint?
    1. @Before
    2. public void init () {
    3. ApplicationContext CTX = new Filesystemxmlapplicationcontext ( "classpath:spring/spring-basic.xml");
    4. Basedao = (ibasedao) Ctx.getbean ("basedao");
    5. Assertnotnull (basedao);
    6. }


When developing spring-based applications, if you also use JUnit for unit testing, you miss the most important hard dish in spring feast.

Before we go into this dish, let's talk about the problem of using JUnit directly for unit testing in a spring-based javaweb project. 1) causes multiple spring container initialization problems

Depending on the invocation process of the JUnit test method, each test method executes creates an instance of the test case and calls the setup () method. As a general rule, we initialize the spring container in the setup () method, which means that if there are many test methods for the test case, the spring container is repeatedly initialized multiple Times. Although it is not too slow to initialize the spring container, it is possible to perform time-consuming operations such as loading the hibernate mapping file when the spring container is initialized, and if the spring container must be initialized repeatedly for each test method, the impact on the performance of the test is not negligible;

With the spring test suite, the spring container is initialized only once!

2) require a hard-coded way to get the bean manually

In the test case class we need to get the target bean that needs to be tested from the SPIRNG container through the Ctx.getbean () method, and also perform a styling operation that enforces the type Conversion. This tedious operation mist in the code of the test case, which makes people feel cumbersome;

Using the spring test suite, the properties in the test case class are automatically populated with the corresponding bean for the spring container
, you do not need to set bean! manually

3) database site vulnerable to damage

Test method changes to the database are persisted to the Database. Although it is for the development database, it may affect the subsequent test behavior if the impact of the data operation is Persistent. For example, the user inserts a user record with ID 1 in the test method, and the first run will not have a problem, and the second run will cause the test case to fail because of a primary key Violation. therefore, it should be able to complete the functional logic check, but also can restore the scene after the test is completed, will not leave "sequela";

With the spring test suite, spring will automatically roll back the operation of the database after you validate it, ensuring that the database is not destroyed, so there is no problem with duplicate testing!

4) inconvenient to check the correctness of data operation

If we insert a successful login log into the log table, we do not check whether a record is actually added to the T_login_log table. In general, we may open the database and visually observe if the corresponding record is inserted, but this is a serious violation of the principle of automated testing. Imagine how to check with the naked eye when testing a program that includes thousands of data manipulation Behaviors.

As long as you inherit the use case class of the spring test suite, you can access the database through JdbcTemplate in the same transaction, query the data changes, verify the correctness of the operation!
After reading the above, I believe you already know what I mean by the hard Dish. Let's look at how the code becomes elegant after using the spring test Suite. 1. Join the Dependency package

Using Spring's test framework requires adding the following dependency packages:

    • JUnit 4
    • Spring Test (test package in spring framework)
    • Spring related other dependencies (no more, It's the context Package)
If you use maven, add the following dependencies in your spring-based project: [html]View PlainCopyprint?
  1. <dependency>
  2. <groupId>junit</groupId>
  3. <artifactid>junit</artifactid>
  4. <version>4.9</version>
  5. <scope>test</scope>
  6. </Dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactid>spring-test</artifactid>
  10. <version> 3.2.4.RELEASE </version>
  11. <scope>provided</scope>
  12. </Dependency>


2. Create test source catalogs and packages

here, It is recommended to create a source file directory with SRC peers, because the classes within SRC are prepared for future products, and the classes here are for testing purposes only. and the name of the package can be the same as the directory in src, so because in the test source directory, so there is no conflict, and the name is identical, more convenient to Retrieve. This is also the Maven Agreement.

3. Create a test class 1) the base class is actually used to load the configuration file   [java]View PlainCopyprint?
  1. @RunWith (springjunit4classrunner. Class) //use junit4 for testing
  2. @ContextConfiguration
  3. ({"/spring/app*.xml","/spring/service/app*.xml"}) //load configuration file
  4. ------------if you add the following code, all test classes that inherit the class will follow that configuration, or not, on the test Class's Method///control transaction, See next instance
  5. This is critical, and if you do not add this annotation configuration, the transaction control will be completely invalidated!
  6. @Transactional
  7. The transaction here is associated to the transaction controller in the configuration file (transactionmanager = "transactionmanager"), and//specifies an automatic rollback (defaultrollback = true). The data in this operation will not pollute the database!
  8. @TransactionConfiguration (transactionmanager = "transactionmanager", Defaultrollback = True)
  9. //------------
  10. Public class Basejunit4test {
  11. }



2) followed by our own test class
[java]View PlainCopy print?
  1. Public class Userassignservicetest extends basejunit4test{
  2. @Resource //automatic injection, By default by name
  3. Private Ibasedao basedao;
  4. @Test //marking is a test method
  5. @Transactional //indicate that this method needs to use a transaction
  6. @Rollback (False) //indicates that the transaction does not roll back after using this method, and true is a rollback
  7. Public void Insert () {
  8. String sql="insert into user (name,password) values (?,?)";
  9. object[] objs=New object[]{"xx","000"};
  10. Basedao.insert (sql, objs);
  11. String sql1="select * from user where name=? and password=?  ";
  12. list<map<string,object>> list=basedao.queryforlist (sql1, objs);
  13. System.out.println (list);
  14. Asserttrue (list.size () >0);
  15. }
  16. }

Original: http://blog.csdn.net/shan9liang/article/details/40452469

Talk about unit tests (iii)--spring test+junit perfect combination

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.