在测试类中,每个测试方法都有以下两行代码
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
这两行代码的作用是获取容器,如果没有,直接会提示空指针异常。
2、解决方案让SpringJunit负责创建Spring容器,但是需要进行测试Bean直接在测试类中进行注入
3、Spring集成Junit步骤(1)导入spring集成Junit的坐标
(2)使用@Runwith注解替换原来的运行期
(3)使用@ContextConfiguration指定配置文件或配置类
(4)使用@Autowired注入需要测试的对象
(5)创建测试方法进行测试
创建xml配置文件
4.0.0 Spring_ssm2 itheima_spring_ioc_annotation 1.0-SNAPSHOT mysql mysql-connector-java 5.1.32 c3p0 c3p0 0.9.1.2 com.alibaba druid 1.1.10 junit junit 4.12 org.springframework spring-context 5.0.5.RELEASE org.springframework spring-test 5.0.5.RELEASE
创建java文件
package com.itheima.test;
import com.itheima.config.SpringConfiguration;
import com.itheima.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;
import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}



