欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring3.0 单元测试

程序员文章站 2022-04-30 15:16:36
...

spring3.0.0之后的版本,官方极力推荐使用如下方式做单元测试。

 

跟junit的单测方式没有大的区别,但是对配置文件的加载,bean的注入灵活了许多。根据官方手册,简单记录下。

 

1. 配置文件加载

    方式一:

 

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
// in the root of the classpath
@ContextConfiguration({"/applicationContext.xml", "/applicationContext-test.xml"})
public class MyTest {
   // class body...
}

    方式二:

 

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/base-context.xml" in the root of the classpath
@ContextConfiguration("/base-context.xml")
public class BaseTest {
   // class body...
}
// ApplicationContext will be loaded from "/base-context.xml" and "/extended-context.xml"
// in the root of the classpath
@ContextConfiguration("/extended-context.xml")
public class ExtendedTest extends BaseTest {
   // class body...
}

 

2. spring bean的注入及使用

 

@RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration("daos.xml")
public final class HibernateTitleDaoTests {
// this instance will be dependency injected by type
@Autowired
private HibernateTitleDao titleDao;
public void testLoadTitle() throws Exception {
   Title title = this.titleDao.loadTitle(new Long(10));
    assertNotNull(title);
}
}

 

 

参考资料:

http://static.springsource.org/spring/docs/3.0.0.RELEASE/reference/htmlsingle/spring-framework-reference.html

 

相关标签: spring-test 3.0.0