Spring Test consolidates JUnit 4 Usage Summary

Source: Internet
Author: User
Tags constructor

After two days of web development and discovering object management through spring, testing became complicated. Because all the beans need to be loaded in the Applicationcontext.xml, and then through the @resource to obtain. It is inefficient and cumbersome to test the entire business flow every time it is done. It's too tedious to write a test class alone. So I think spring has a test framework that can integrate junit for testing, so take it out and try it . 1. Join a Dependency package

Using Spring's test framework requires the following dependency packages: JUnit 4 (official download: http://www.junit.org/) Spring Test (Test package in spring Framework) spring related other dependencies (no more, is the context etc package) 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. 3. Create a test class

Create a test class with the recommended name "tested class name + Test".

The test class should inherit with Abstractjunit4springcontexttests or abstracttransactionaljunit4springcontexttests

For abstractjunit4springcontexttests and Abstracttransactionaljunit4springcontexttests classes, choose from:

If you need to use transaction management in your test class (for example, to roll back the test content after the test results have been rolled out), the Abstracttransactionaljunit4springtests class can be used. The use of transaction management is the same as the normal use of spring transaction management. It is important to note that if you want to use declarative transaction management, you use the Abstracttransactionaljunitspringcontexttests class, Please include the TransactionManager bean in the Applicationcontext.xml file:

<bean id= "TransactionManager"
class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name= "DataSource" ref= "DataSource"/>
</bean>

If this bean is not added, Nosuchbeandefinitionexception will be thrown, indicating no bean named ' TransactionManager ' is definded.
4. Configuring the Test class

Add the following in front of class to configure the location of the Applicationcontext.xml file.

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (locations = "Classpath:applicationContext.xml")
5. Create a test method

To create a test method, the recommended name is "test method name + test".

Add @Test above the test method 6. Execute via JUnit 4

Right-click the method name and select "Run as" → "JUnit Test" to

Appendix 1: Overall test class files

/* @ (#) Userdaotest.java
*
*/
Package Com.phj.dao;

Import Javax.annotation.Resource;

Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.test.context.ContextConfiguration;
Import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

Import Com.phj.entity.User;

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (locations = "Classpath:applicationContext.xml")
public class Userdaotest extends Abstractjunit4springcontexttests {

@Resource
Private Userdaointerface Userdao;

@Test
public void Savetest () {

User User1 = new user ();
User1.setusername ("Tom");
User1.setpassword ("123456");
User1.setnickname ("Tom");
User1.setemail ("tom@gmail.com");

User User2 = new user ();
User2.setusername ("admin");
User2.setpassword ("123456");
User2.setnickname ("admin");
User2.setemail ("admin@admin.com");

User User3 = new user ();
User3.setusername ("Feihong");
User3.setpassword ("123456");
User3.setnickname ("PhJ");
User3.setemail ("test@gmail.com");

Userdao.save (user1);
Userdao.save (User2);
Userdao.save (USER3);
}
}

OK, so you can use the Spring test framework.


When using annotations, JUnit error:

[Java]  View plain copy java.lang.nosuchfielderror: null       at  Org.junit.runners.parentrunner.<init> (parentrunner.java:48)        at  Org.junit.runners.blockjunit4classrunner.<init> (blockjunit4classrunner.java:59)         at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init> ( springjunit4classrunner.java:104)        at  Sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native method)         At sun.reflect.nativeconstructoraccessorimpl.newinstance (nativeconstructoraccessorimpl.java:39)         at sun.reflect.delegatingconstructoraccessorimpl.newinstance ( DELEGATINGCONSTRUCTORACCESSORIMPL.JAVA:27)        at  Java.lang.reflect.Constructor.newInstance (constructor.java:513)         At org.junit.internal.requests.classrequest.buildrunner (classrequest.java:33)         at org.junit.internal.requests.classrequest.getrunner (classrequest.java:28)         at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init> ( JUNIT4TESTREFERENCE.JAVA:28)   

Check is a jar package conflict, I was in the project, MyEclipse automatically joined JUNIT4, and later I joined Junit4.8.1.


If the following error is reported, the JUnit package version is too low and requires 4.5 or more versions

[Java] view plain copy caused By:java.lang.ClassNotFoundException:org.junit.runners.BlockJUnit4ClassRunner At Java.net.urlclassloader$1.run (urlclassloader.java:200) at java.security.AccessController.doPrivileged (Nat Ive Method) at Java.net.URLClassLoader.findClass (urlclassloader.java:188) at Java.lang.ClassLoader.loadCla SS (classloader.java:307) at Sun.misc.launcher$appclassloader.loadclass (launcher.java:301) at Java.lang.Cla Ssloader.loadclass (classloader.java:252) at java.lang.ClassLoader.loadClassInternal (classloader.java:320)


Other questions:

@ContextConfiguration ({"Classpath:applicationContext.xml", "classpath:spring/buyer/ Applicationcontext-service.xml "})
Import the configuration file, where my ApplicationContext profile is categorized according to the module. Multiple "applicationcontext-service.xml" files are introduced if more than one module is available. If all is written in "ApplicationContext. XML "is imported in this way:
@ContextConfiguration (locations = "Classpath:applicationContext.xml")
@RunWith (Springjunit4classrunner.class) Springjunit support, thus introducing spring-test framework support.
@Transactional This is critical, if you do not add this annotation configuration, the transaction control will be completely invalidated.
@TransactionConfiguration (TransactionManager = "TransactionManager", Defaultrollback = True) The transaction here is associated to the transaction controller (TransactionManager = "TransactionManager") in the configuration file, and also specifies an automatic rollback (Defaultrollback = true). The data in this operation does not contaminate the database.
Abstracttransactionaldatasourcespringcontexttests the base class must be found to build this series of non-polluting, pure green transaction testing frameworks. (That is, all transactions do not take effect)


import com.wonders.frame.ias.service.IasScheduleTask; import org.junit.Test; import
Org.junit.runner.RunWith;
Import org.springframework.stereotype.Component;
Import org.springframework.test.context.ContextConfiguration;
Import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner; Import Org.springframework.transaction.annotat 

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.