"Spring" JUnit loading spring containers for unit testing
Read Catalogue
- > Basic Construction
- > Common usage
If we need to do unit testing of our service methods, and just like spring as an IOC container, we can configure JUnit to load the spring container so that it is easy to do unit testing.
> Basic Construction
(1) Introduce the required package
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope></dependency><dependency > <groupId>org.springframework</groupId> <artifactid>spring-test</artifactid > <version>3.2.10.RELEASE</version></dependency>
(2) Write test class
In the test class you want to set which spring configurations to load (I'm "/config/application*.xml" here), and then I can inject the beans in the container.
PackageCom.nicchagil.mybatis3spring3intg.junit;ImportJava.util.List;ImportOrg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;Import Com.nicchagil.mybatis3spring3intg.bean.User; import Com.nicchagil.mybatis3spring3intg.service.UserService; @RunWith (Springjunit4classrunner.) @ContextConfiguration ({"/config/application*.xml" public class Junittest {@Autowired private UserService UserService ; @Test public void C1 () { List<user> userlist = userservice.query (new User ()); System.out.println (userlist); }}
> Common usage
The common way is to share the part of the load configuration:
Package Com.nicchagil.mybatis3spring3intg.junit; Import Org.junit.runner.RunWith; Import org.springframework.test.context.ContextConfiguration; Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith (Springjunit4classrunner. Class) @ContextConfiguration ({"/config/application*.xml"})class Basejunit {}
Then the individual test classes that are required inherit the common class:
PackageCom.nicchagil.mybatis3spring3intg.junit;ImportJava.util.List;ImportOrg.junit.Test;Import org.springframework.beans.factory.annotation.Autowired; import Com.nicchagil.mybatis3spring3intg.bean.User; import Com.nicchagil.mybatis3spring3intg.service.UserService; public class userservicetest extends Basejunit {@Autowired private UserService UserService; @Test public void C1 () {list<user> userlist = Userservice.query (new User ()); System.out.println (userlist); }}
"Spring" JUnit loading spring containers for unit testing (GO)