如何使用Spring-Test对Spring框架进行单元测试

这篇文章主要介绍了如何使用Spring-Test对Spring框架进行单元测试,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Spring-Test对Spring框架进行单元测试

配置过程:

加载依赖

引入Maven依赖:

  org.springframeworkspring-test${springframework}test

编写SpringTestBase基础类,加载所需xml文件

 import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(locations = { "classpath:Application-Redis.xml" }) @RunWith(SpringJUnit4ClassRunner.class) public class SpringTestBase extends AbstractJUnit4SpringContextTests { } 

将所需加载的xml文件指定为locations的value。

编写单元测试类 示例

直接继承SpringTestBase 就可以对Spring框架的内容进行单元测试。

 import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class TestRedisCacheDaoImpl extends SpringTestBase { @Autowired public RedisCacheDaoImpl redisCacheDaoImpl; @Test public void testPing() { boolean reslut = redisCacheDaoImpl.ping(); Assert.assertEquals(true, reslut); } } 

Spring-Test测试数据

1、新建一个maven项目

2、pom.xml当中添加依赖

   org.springframeworkspring-webmvc5.2.5.RELEASE org.springframeworkspring-test5.2.5.RELEASE junitjunit4.12test

spring-test是Spring当中的测试包,而junit是单元测试包,结合起来使用。

添加一个bean,便于测试。

HelloService.java

 @Service public class HelloService { public String hello(String name) { return "hello " + name; } }

添加配置文件扫描包:

    

3、测试方法

 @ContextConfiguration("classpath:applicationContext.xml") @RunWith(SpringJUnit4ClassRunner.class) public class Test { @Autowired HelloService helloService; @org.junit.Test public void test(){ System.out.println(helloService.hello("youyuan")); } } 

以上就是如何使用Spring-Test对Spring框架进行单元测试的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java