Spring 学习总结笔记【四、整合Junit】

往期文章:

Spring 学习总结笔记【一、快速入门】
Spring 学习总结笔记【二、IoC-控制反转】
Spring 学习总结笔记【三、注解开发】

一、前言

在前面篇章提到的Spring的测试类中,每个测试方法都有以下两行代码:

ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = app.getBean("bookDao", BookDao.class);

这两行代码作用是获取容器,如果省略不写,会出现空指针异常。所以又不能轻易删除。

二、解决思路

  • 使用SpringJunit创建Spring容器,但是需要将配置文件名称告诉它。
  • 将需要进行测试的Bean直接在测试类中进行注入。

三、整合Junit开发步骤

① 导入Spring集成Junit的坐标

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<version>5.0.5.RELEASE</version>
</dependency>

② 使用@Runwith注解替换原来的运行期

@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {

}

③ 使用@ContextConfiguration指定配置文件或配置类

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = SpringConfig.class)
public class SpringJunitTest {

}

④ 使用@Autowired注入需要测试的对象

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(value = {"classpath:applicationContext.xml"})
@ContextConfiguration(classes = {SpringConfig.class})
public class SpringJunitTest {

    @Autowired
    private BookService bookService;

	// 测试查询
    @Test
    public void test1(){
        bookService.save();
    }
}

下期文章

Spring 学习总结笔记【五、配置数据源】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值