在Spring中可以使用junit配合注解进行单元测试
一、常用注解
1、@RunWith(SpringJUnit4ClassRunner.class),让测试运行于spring测试环境
2、@ContextConfiguration 用来指定加载的Spring配置文件的位置,会加载默认配置文件,
@ContextConfiguration 注解有以下两个常用的属性:
locations:可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件用,分开。
inheritLocations:是否要继承父测试用例类中的 Spring 配置文件,默认为 true。
二、常用方法
1、assertEquals(Object expected, Object actual)
比较两者是否相等
三、示例代码 (仅显示测试代码,xml配置、Service层代码略)
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"}) public class UserServiceImplTest { @Autowired private UserServiceImpl userService; @Before public void before() throws Exception { } @After public void after() throws Exception { } @Test public void testGetUserById() throws Exception { //TODO: Test goes here... Assert.assertEquals( "lin" , userService.getUserById(2).getUserName()); } }