First, to introduce the spring jar file into the project, I adopted the jar package that Maven managed the project depends on:
<Properties> <spring.version>4.0.0.RELEASE</spring.version></Properties><Dependency> <groupId>Org.springframework</groupId> <Artifactid>Spring-test</Artifactid> <version>${spring.version}</version></Dependency>
The project directory structure is as follows:
You also need to introduce JUNIT4 jar packages into your project
Second, write test class
The Jdbctransactiontest.java in the structure is the part of the test class whose code is as follows:
@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations= "Classpath:applicationContext_jdbc_transaction.xml") Public classJdbctransactiontestextendsabstractjunit4springcontexttests {@Test Public voidTransactiontest ()throwsclassnotfoundexception, Instantiationexception, Illegalaccessexception, SQLException {Class.fornam E ("Oracle.jdbc.driver.OracleDriver"). newinstance (); String URL= "Jdbc:oracle:thin: @localhost: 1521:xxxxxxxx"; String User= "xxxxxxx"; String Password= "XXXX"; Connection Conn=NULL; Statement Statement=NULL; Try{conn=drivermanager.getconnection (URL, user, password); Conn.setautocommit (false); Statement=conn.createstatement ();String sql = "INSERT into user_base values (1, ' James ', ' AAA ', 2,12)"; Statement.executeupdate (SQL); Conn.commit (); } Catch(SQLException e) {if(Conn! =NULL) Conn.rollback (); Conn.close (); Statement.close (); } }}
Requirement: The class must inherit from Abstractjunit4springcontexttests
Then write the method in it and comment on the method: @Test
Add a comment at the top of the class: @RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations = "Classpath:applicatio Ncontext.xml ")
This allows you to test the development by configuring the location of the spring configuration file.
Iii. acquiring an IOC container in a test class
In Abstractjunit4springcontexttests, there is a definition of the ApplicationContext variable, which is the global IOC container of spring, through which you can get the beans defined in the XML
To make it easy to get a custom bean by name, we can encapsulate the applicationcontext into a method, provide a custom bean externally with the name of a given bean, or provide it to an external applicationcontext:
Public Object Getbean (String beanname) { return Applicationcontext.getbean (beanname);} protected ApplicationContext GetContext () { return applicationcontext;}
Spring-test Usage Introduction