Spring框架|Spring的单元测试


使用Spring的单元测试的好处

不需要再使用ioc.getBean()来获取组件了,直接Autowired组件,Spring为其自动装配。

  • Spring完美的支持了Junit4(提供特别的 SpringJunit4ClassRunner),比较好的支持了 TestNG。
  • 在支持原有单元测试能力的基础上,通过各种监听器,支持了测试类的依赖注入、对 Spring applicationContext 的访问以及事务管理能力,为使用 Spring 架构的应用程序的测试带来了极大的便利性

使用步骤

1、导包:Spring的单元测试首先需要导入Spring的单元测试包。
2、加载文件:@ContextConfiguration(locations = "calsspath:applicationContext.xml")
3、加载Spring的驱动:@RunWith(SpringJUnit4ClassRunner.class)

  • @RunWith()指定使用哪种驱动进行单元测试,默认是JUnity,需要更改为Spring自带的。

演示使用Spring单元测试

控制层

@Controller
public class BookServlet {
	@Autowired
	private BookService bookservice;

	public void doGet() {
		bookservice.save();
	}
}

业务层

@Service
public class BookService {
	@Autowired
	private BookDao bookDao;

	public void save() {
		System.out.println("正在调用BookDao进行保存图书..");
		bookDao.saveBook();
	}
}

数据访问层


@Repository
public class BookDao {
	public void saveBook() {
		System.out.println("图书保存成功...");
	}
}

使用Spring的单元测试Test:

  • @ContextConfiguration(locations = “calsspath:applicationContext.xml”):指明配置文件的类路径。
  • @RunWith(SpringJUnit4ClassRunner.class):表明使用Spring的驱动进行测试。
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class iocTest {
	@Autowired
	BookServlet bookServlet;

	@Test
	public void test01() {
		bookServlet.doGet();
	}
}

运行测试程序,成功完成Spring单元 测试:
在这里插入图片描述

发布了451 篇原创文章 · 获赞 1428 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/105053235
今日推荐