SPRINGJUNIT4 Unit Testing (example--immediately preceding chapter)

Source: Internet
Author: User

Objective:

  When we did a Web project, we wrote a DAO and a service, and then we had to do the unit test , and then we had to wait until the spring container was loaded. And then by getting the ApplicationContext object to Gerbean () method to test, or even more stupid to write a controller, in the browser-typed address debug tracking test, so not only inefficient, and very little effect.

This chapter explains the Spring Fusion JUNIT4 for unit testing.

The test source catalogs and packages in this chapter are the source code that follows the previous chapter. point I see the previous chapter

Preparatory work:

    •  Jar package support (given in the previous section code)
    • Source code and package structure of the test (IBID.)
    • Note: Testing the test package path is best located in the src root directory, compiled for the Calsses folder, easy to write other paths

Example code Demo:

Copy the class to the first section of the test package to ************ the comment section I'll explain as much as I can about ****************

Userservicetest

 Packagetest;Importjava.util.List;ImportJavax.annotation.Resource;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.FileSystemXmlApplicationContext;ImportOrg.springframework.data.domain.Page;Importorg.springframework.data.domain.PageRequest;Importorg.springframework.data.domain.Sort.Direction;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;Importorg.springframework.test.context.transaction.TransactionConfiguration;Importorg.springframework.transaction.annotation.Transactional;ImportCom.spring.jpa.user.User;ImportCom.spring.jpa.user.UserService;/**The declaration is using Spring's test class **/@RunWith (Springjunit4classrunner.class)/**Declare the Spring Master profile location, note: The position of the current test class is benchmarked, and multiple profiles are declared with a character array **/@ContextConfiguration (Locations={".. /spring-config/spring-jpa.xml "})/**declares using transactions, does not declare spring uses default transaction management **/@Transactional/**declaring a transaction rollback, or testing a method data is not a very cup of tea, note: When inserting data, you can bet it off and not let the transaction roll back **/@TransactionConfiguration (TransactionManager= "TransactionManager", defaultrollback=true) Public classuserservicetest {@ResourcePrivateUserService UserService; @Test//New (20 data) Note that when you add a transaction, you are not going to roll back the operation     Public voidTestsaveuser () { for(inti=0; i<20; i++) {User User=NewUser (); User.setusername ("System"); User.setpassword (i+ "System");        Userservice.saveuser (user); }} @Test//Delete a transaction rollback that does not really delete     Public voidTestdeleteuser () {Userservice.deleteuser (27L); } @Test//Query All     Public voidTestfindalluser () {List<User> users =userservice.findallusers ();    System.out.println (Users.size ()); } @Test//Querying paged Objects     Public voidTestfindalluserbypage () {/*** Create a Paging object (note: 0 is the first page, 5 represents the size of each page, the latter two parameters are the default sort) * Direction: For an enumeration class, the DESC and ASC sort order * IDs are defined: The result set is based on the ID for desc descending sort * If you want to implement it yourself, it's best to inherit his class to define some of the ways of personality.*/pagerequest Request=NewPagerequest (1, 4, DIRECTION.DESC, "id"); Page<User> users =userservice.findalluserbypage (Request); //Print pagination DetailsSYSTEM.OUT.PRINTLN ("Query results: Total" +users.gettotalelements () + "bar data, each page shows" +users.getsize () + "bar, Total" +users.gettotalpages () + "page , the current section "+ (Users.getnumber () +1) +" Page! "); //Print the contents of a result setSystem.out.println (Users.getcontent ()); }        //main is used to view all spring beans in order to detect if the spring container is properly initialized     Public Static voidMain (string[] args) {//I use absolute path here, please configure according to the path of your project (relative path can not dig out-out)String [] path = {"E:/moviework/springjpa/src/spring-config/spring-jpa.xml"}; ApplicationContext AC=Newfilesystemxmlapplicationcontext (path); string[] Beans=Ac.getbeandefinitionnames ();  for(String S:beans) {System.out.println (s); //Print the name of the bean         }    }}

Test the testfindalluserbypage() method console output SQL statements and information:

Done, it is so simple, and ordinary Java class testing is just the annotated thing. The principle is the same, and it supports rollback of transactions without worrying about destroying the data at the time of the test. The Web project test of the original spring framework can be as concise as you can understand.

The data is based on the previous chapter, and this section is no longer posted, and the project is packaged in the previous section. point me to the previous chapter

Summarize:

    • When writing the test class, it is easier to read and write code in the SRC directory.
    • Follow the test specification, the test class method name is: Test + original method name Capital letter
    • Note A reference to the @contextconfiguration annotation path

writing is not easy, inevitably there are omissions and mistakes, but also please be generous, feel helpful to help recommend Oh

PS: Welcome reprint, reproduced please indicate the source: http://www.cnblogs.com/liuyitian/p/4063033.html

                                         Learn a little bit more everyday code less knock a little bit

SPRINGJUNIT4 Unit Testing (example--immediately preceding chapter)

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.