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;ImportCom.nicchagil.mybatis3spring3intg.bean.User;ImportCom.nicchagil.mybatis3spring3intg.service.UserService; the @RunWith (Springjunit4classrunner.class) @ContextConfiguration ({"/config/application*.xml"}) Public classjunittest {@AutowiredPrivateUserService UserService; @Test Public voidC1 () {List<User> userlist = Userservice.query (NewUser ()); 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; the @RunWith (Springjunit4classrunner. class ) @ContextConfiguration ({"/config/application*.xml"})publicclass basejunit { }
Then the individual test classes that are required inherit the common class:
PackageCom.nicchagil.mybatis3spring3intg.junit;Importjava.util.List;Importorg.junit.Test;Importorg.springframework.beans.factory.annotation.Autowired;ImportCom.nicchagil.mybatis3spring3intg.bean.User;ImportCom.nicchagil.mybatis3spring3intg.service.UserService; Public classUserservicetestextendsBasejunit {@AutowiredPrivateUserService UserService; @Test Public voidC1 () {List<User> userlist = Userservice.query (NewUser ()); System.out.println (userlist); }}
"Spring" JUnit loading spring containers for unit testing