问题:单元测试报null
我是想测试一下连接数据库是否成功,结果报了null,
@Autowired
DataSource dataSource;
@Test
public void Naa() throws SQLException {
Connection con=dataSource.getConnection();
System.out.println(con);
}
报错如下:
解决
以前遇到过,后来忘记怎么处理了,翻了一下以前的代码,对比了一下,发现原因是我使用了@Autowired,因为在单元测试时,容器里的配置注册不了,所以报null
第一种方法:ApplicationContext(不推荐)
通过ApplicationContext context获取配置文件上下文,然后通过getBean直接获取想要注入的类,这种只能通过getBean获取指定的Bean,要是想注入很多类,是很麻烦的。
public class Aaa {
@Test
public void Naa() throws SQLException {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource=(DataSource) context.getBean("dataSource");
Connection con=dataSource.getConnection();
System.out.println(con);
}
}
测试成功
第二种方法:通过注解(推荐)
在测试类上加入@RunWith和@ContextConfiguration注解
@RunWith:运行器;
@ContextConfiguration:引入配置文件,可以引入多个或单个;
通过@ContextConfiguration指定要用到的配置文件,就可以使用@Autowire等;
代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml","classpath:applicationContext123.xml"})
public class CrowdFundingTest {
@Autowired
private DataSource dataSource;
@Test
public void test() throws SQLException {
Connection con=dataSource.getConnection();
System.out.println(con);
}
}
测试成功
applicationContext.xml
配置个数据源就可以了,放在src下,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
destroy-method="close">
<property name="url" value="jdbc:oracle:thin:@localhost:1521/orcl" />
<property name="username" value="NEW_DDSYS" />
<property name="password" value="dd" />
</bean>
</beans>
指定包的位置
//applicationContext.xml在包com.test.wu下面
@ContextConfiguration(locations = "classpath*:/com/test/wu/applicationContext.xml")