Spring_继承junit步骤
- 导入spring集成Junit的坐标
- 使用@Runwith注解替换原来的运行期
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
package com.lzy.test;
import com.lzy.config.SpringConfiguration;
import com.lzy.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
@RunWith(SpringJUnit4ClassRunner.class) //指定使用SpringJunit测试
//导入配置文件
//@ContextConfiguration("classpath:applicationContext.xml")
//导入配置类
@ContextConfiguration(classes= SpringConfiguration.class)
public class SpringJunitTest {
@Autowired //从Spring容器中获取UserService
private UserService userService ;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws Exception {
userService.save();
System.out.println(dataSource.getConnection());
}
}