当我们使用Junit进行代码测试时,一般是这样的格式
1 public class Test { 2 3 @org.junit.Test 4 public void test2(){ 5 System.out.println(111); 6 } 7 }
当我们想要在测试类使用@Autowired自动注入时,就必须使用@RunWith注解和@ContextConfiguration注解
比如我要使用JdbcTemplate时。
现在我使用的方式是xml
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(locations = {"classpath:spring_config.xml"}) 3 public class Test { 4 @Autowired 5 JdbcTemplate jdbcTemplate; 6 @org.junit.Test 7 public void test1() { 8 String sql="insert into study values(?,?)"; 9 int update = jdbcTemplate.update(sql, 3,"one"); 10 System.out.println(update); 11 } 12 13 }
这是spring_config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx.xsd 12 http://www.springframework.org/schema/aop 13 http://www.springframework.org/schema/aop/spring-aop.xsd 14 http://www.springframework.org/schema/context 15 http://www.springframework.org/schema/context/spring-context.xsd"> 16 <!--自动扫描--> 17 <context:component-scan base-package="com.zktr"></context:component-scan> 18 <!--设置jdbcTemplate配置--> 19 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 20 <property name="dataSource" ref="datasouse"></property> 21 </bean> 22 <!--设置数据库配置--> 23 <bean id="datasouse" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 24 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 25 <property name="url" value="jdbc:mysql://localhost:3306/test"></property> 26 <property name="username" value="root"></property> 27 <property name="password" value="root2019"></property> 28 </bean> 29 </beans>
@ContextConfiguration
括号里的locations = {"classpath:spring_config.xml"}
指定了一个xml文件,那么这个XML文件配置的bean或者扫描下来的bean就都可以拿到了,此时就可以在测试类中使用@Autowired
注解