JUnit4注解测试SSH

JUnit,大家并不陌生,对于普通的项目测试,我们只需要继承TestCase即可,但是对于SSH我们需要考虑到SpringDI注入,这就需要用到JUnit4注解来测试SSH

 

一、为何用JUnit4

   我先来说下为什么之前的JUnit的简单继承TestCase的测试不能测试SSHWeb项目,大家都知道,我们启动Web项目时要先启动Tomcat,而在Tomcat的启动过程中会读取SSH的各个配置文件,实例化各个注入的类,所以我们的程序中直接使用注解就可以操作各个类。

 

   但是如果是单击的继承TestCase的类,就缺少了读取配置文件的过程,所以当你调用一个类方法时会出现空指针错误,因为类没有实例化。

 

二、JUnit4使用

   Junit4的特点就是使用注解,简化了我们的测试代码,测试之前,先引入spring-test.jarjunit4.4.jar

 

   首先我们可以写一个公共或万能的spring-test的基类,这样需要使用时直接继承即可


package cn.xkshow.framework.service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import cn.xkshow.framework.dao.hibernate.UniversalDao;
import cn.xkshow.plugins.page.PageList;
import cn.xkshow.plugins.page.Page;

@Service
public class UniversalService {	
	private UniversalDao universalDao;
	
	public void save(Object entity) {
		this.universalDao.save(entity);
	}
	
	public void saveOrUpdate(Object entity) {
		this.universalDao.saveOrUpdate(entity);
	}
	
	
	public void setUniversalDao(UniversalDao universalDao) {
		this.universalDao = universalDao;
	}

}
package cn.xkshow.framework.service;

import static org.junit.Assert.*;
import javax.annotation.Resource;

import org.junit.After;
import org.junit.Before;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UniversalServiceTest extends AbstractJUnit4SpringContextTests  {
	@Resource
	protected UniversalService universalService;
	
	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

}

    接下来再写一个具体的测试


package cn.xkshow.core.authorization.service;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;

import cn.xkshow.core.authorization.po.Module;
import cn.xkshow.framework.service.UniversalServiceTest;

public class UniversalServiceTureTest extends UniversalServiceTest {
	@Test
	public void testSave() {
		User obj = new User();
         obj.setName("张三");
         universalService.save();		
	}
	
}


OK!



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值