Background
If spring project needs to test small functions, it takes time and effort to start the whole project. You can use spring test package to unit test, accelerate project development and testing.
Two, use
1. Add maven dependency
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.21.RELEASE</version> </dependency>
2. Create test class
Select the class to be tested, cmd+shift+T shortcut key, and create the test class.
2.1 configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans default-autowire="byName" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--Use property file--> <context:property-placeholder location="classpath:application.properties" order="1" ignore-unresolvable="true" /> <!-- data base --> <!--Data source configuration--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="simpleJdbcDao" class="database.dao.SimpleJdbcDao"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
2.2 write test class and reference configuration file
package database.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath*:/acTest.xml" }) public class SimpleJdbcDaoTest { @Autowired @Qualifier("simpleJdbcDao") private JdbcDaoSupport jdbcDaoSupport; @Test public void testJdbcDaoSupport() { String sql = "select * from user"; List list = jdbcDaoSupport.getJdbcTemplate().queryForList(sql); System.out.println(list); } }
2.3 configuration file placement path
@Contextconfiguration (locations = {"actest. XML"}) needs to be placed under the path of the compiled SimpleJdbcDaoTest.class file @Contextconfiguration (locations = {"classpath *: / actest. XML"}) is placed under the / src/test/resources path and copied to the / target / test classes / actest.xml path after execution.