您的位置:首页 > 其它

关于单元测试的学习记录

2016-05-05 23:12 274 查看
在开发过程中,单元测试必不可少,针对本人开发经验(主要是整合Spring、Mybatis等开发框架)

归纳以下俩种单元测试,当作学习笔记和作为简单总结,后期如有接触新的方式,再进行修改。

1、基于Spring的单元测试(注解方式):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/spring-mybatis.xml")
public class DeptServiceImplTest {

@Resource(name="deptService")
private DeptService deptService;

@Test
public void testFindAll() {
System.out.println(this.deptService.findAll());
}

@Test
public void testUpdate() {
Dept dept = this.deptService.getById("1");
dept.setDirect("院长");
dept.setName("计算机");
this.deptService.update(dept);
}

}
2、基于junit的单元测试
public class DemoTest {

private DemoService demoService;

@Before<span style="white-space:pre"> </span>
public void before(){
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"classpath:conf/spring.xml",
"classpath:conf/spring-mybatis.xml"});
demoService = (DemoService) context.getBean("demoServiceImpl");
}

@Test
public void testCount() {
System.out.println(this.demoService.count(null));
}

@Test
public void testFindDemos() {
List<Demo> lists = this.demoService.findDemos(null, 0, "50");
for(Demo d : lists){
System.out.println(d);
}
}

}

这里对junit单元测试常用注解作一个简单介绍:
有: @BeforeClass 、@Before、@Test、@After、@AfterClass

理解起来也非常简单:

如果我们是对整一个单元测试类做测试,也就是如:Run as ->Junit Test(即所有含有@Test都会被执行),那么执行的顺序会是 @BeforeClass  > @Before > @Test >  @After> @AfterClass

其中@BeforeClass、@AfterClass只会运行一次,不同的是,@Before和@After在每个测试前后都会运行一次。而@BeforeClass、@AfterClass必须是public static void,@Before和@After则和@Test一样,都是public void(想想运行测试就可以知道为什么不是静态(static)的)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单元测试