SpringJunit4 performs unit testing (instance-next to the previous chapter) and springjunit4

Source: Internet
Author: User

SpringJunit4 performs unit testing (instance-next to the previous chapter) and springjunit4

Preface:

  After we have written a Dao and a Service for a WEB project, we need to perform a unit test and wait until all the Spring containers are loaded, then, you can get the ApplicationContext object to use the gerBean () method for testing. Alternatively, you can write a controller and press the address in the browser to perform the deBug tracking test. This is not only inefficient, and it has little effect.

This chapter describes spring integrated Junit4 for unit testing.

The test source directories and packages in this chapter follow the source code in the previous chapter.Click here to view the previous chapter

Preparations:

  •  Jar package support (as shown in the code in the previous section)
  • Test source code and Package Structure (same as above)
  • Note: The test package path of the test class is preferably located in the src root directory, which is compiled into the calsses folder to facilitate the writing of other paths.

Demo of instance code:

* **************** Copy this class to the comment section of the test package in the previous chapter. ****************

UserServiceTest

Package test; import java. util. list; import javax. annotation. resource; import org. junit. test; import org. junit. runner. runWith; import org. springframework. context. applicationContext; import org. springframework. context. support. fileSystemXmlApplicationContext; import org. springframework. data. domain. page; import org. springframework. data. domain. pageRequest; import org. springframework. data. domain. sort. direction; I Mport 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; import com. spring. jpa. user. user; import com. spring. jpa. user. userService;/** declare the Spring Test class **/@ RunWith (SpringJUnit4ClassRunner. c Lass)/** declare the location of the spring main configuration file. Note: Based on the location of the current test class, multiple configuration files are declared as character arrays **/@ ContextConfiguration (locations = {".. /spring-config/spring-jpa.xml "})/** declare to use transactions, do not declare spring will use the default Transaction Management **/@ Transactional/** declare transaction rollback, if you want to test the data of a method, you can ignore the data and do not allow the transaction to roll back. **/@ TransactionConfiguration (transactionManager = "transactionManager ", defaultRollback = true) public class UserServiceTest {@ Resource private UserService userService; @ Test // Add (20 data records) Note that the transaction is first injected when the transaction is added. Do not roll back the public void testSaveUser () {for (int I = 0; I <20; I ++) {User user = new User (); user. setUserName ("system"); user. setPassWord (I + "system"); userService. saveUser (user) ;}@ Test // transaction rollback is deleted and public void testDeleteUser () {userService is not deleted. deleteUser (27L);} @ Test // query all public void testFindAllUser () {List <User> users = userService. findAllUsers (); System. out. println (u Sers. size () ;}@ Test // query the Page Object public void testFindAllUserByPage () {/*** to create a Page Object (Note: 0 indicates the first page, 5 indicates the size of each page, and the last two parameters are sorted by default.) * ction: defines the DESC and ASC sorting order for an enumeration class * id: if you want to implement the result set in descending order of DESC by id *, you 'd better inherit this class to define some personalized Methods */PageRequest request = new PageRequest (1, 4, direction. DESC, "id"); Page <User> users = userService. findAllUserByPage (request); // print the page details System. out. println ("query result: total" + users. getTotalElements () + "Data entries, each page shows" + users. getSize () + "entries, total" + users. getTotalPages () + "Page, current section" + (users. getNumber () + 1) + "Page! "); // Print the result set content System. out. println (users. getContent ();} // main is used to view all spring beans, so as to check whether the spring container correctly initializes public static void main (String [] args) {// here I use an absolute path. Please configure it according to the path of your project (the relative path cannot be dug OUT) String [] path = {"E: /moviework/springJpa/src/spring-config/spring-jpa.xml "}; ApplicationContext ac = new FileSystemXmlApplicationContext (path); String [] beans = ac. getBeanDefinitionNames (); for (String s: beans) {System. out. println (s); // print bean name }}}

Test the testFindAllUserByPage () method. The console outputs SQL statements and information:

After all, it's so simple. Much of the testing with common java classes is just annotation. The principle is the same, and it supports transaction rollback without worrying about data corruption during testing. The WEB project testing of the original Spring framework can be as concise as it is.

The data is based on the previous chapter. This chapter is no longer posted, and project packaging is also included in the previous chapter.Click here to go to the previous chapter

Summary:

  • When writing the test class, it is easier to read and write the code in the src directory.
  • According to the test specification, the test method name is: test + the first letter of the original method name is capitalized.
  • Note: @ ContextConfiguration refers to the annotation path.

It is not easy to write, and there are inevitable omissions and errors. Please make generous corrections and feel helpful for recommendations.

Ps: You are welcome to reprint it. Please indicate the source for reprinting:Http://www.cnblogs.com/liuyitian/p/4063033.html

 

Learn a little more code every day

 


Is there a Spring unit test and an instance tutorial download?

Written in the Official Development Manual

----->
It's simplified Chinese in mainland China.

Provided by Xinhua Dictionary
Reference: www.jactiongroup.net/reference2/html/testing.html


Related Article

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.