Spring整合junit,并使程序自动创建spring容器

一、快速使用

1.导入依赖

junit
spring-test

2.测试类上加注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:配置文件位置"})

3.注入测试对象

@Autowired

4.测试方法上加注解

@Test

二、原理详解

junit无法为我们创建spring容器,所以每个测试方法都需要手动获取容器。

例如

package com.yooyo.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yooyo.domain.Account;
import com.yooyo.service.AccountService;

public class AccoutTest {
	@Test
	public void run1() {
	/**
	*获取容器并获取对象,重复代码
	**/
		ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		AccountService accountService = ac.getBean(AccountService.class);
		
		List<Account> list = accountService.findAll();
		System.out.println(list);
	}
	@Test
	public void run2() {
	/**
	*获取容器并获取对象,重复代码
	**/
		ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		AccountService accountService = ac.getBean(AccountService.class);
		
		List<Account> list = accountService.findAll();
		System.out.println(list);
	}
}

但是junit暴露了一个注解@RunWith(SpringJUnit4ClassRunner.class),可以使用它使用spring提供的运行器替换掉junit的运行器。这样我们就可以在测试类中直接使用@Autowired注入对象使用了。

例如

package com.yooyo.test;

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 com.yooyo.service.AccountService;
//1.替换junit的运行器为spring的运行器,该注解为junit提供
@RunWith(SpringJUnit4ClassRunner.class)
//2.替换掉运行器以后,测试类可以为我们创建spring容器了,但是需要知道配置文件的位置,加载配置文件或注解类
@ContextConfiguration(locations= {"classpath:spring/applicationContext.xml"})
public class AccoutTest {
	@Autowired
	private AccountService accountService;
	@Test
	public void run1() {
		System.out.println(accountService.findAll());
	}
	@Test
	public void run2() {
		System.out.println(accountService.findAll());
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值