使用JUnit4对SSH2框架Service/Dao层进行单元测试

  1. JUnit是一个非常好用的测试框架,但在对SSH架构的Java代码中需要注入由Spring管理的Bean,下面就简单介绍一下使用JUnit4对SSHSSH2框架Service/Dao层进行单元测试的方法。
    • 在建立JUnit Test Case 测试类时,勾选setUpBeforeClass,我们需要在setUpBeforeClass()类中加载Spring配置文件。其它步骤和一般的Java测试过程一样(添加测试类的名称,选择需要测试的类和要测试的方法)。
    • 建立好测试类后在setUpBeforeClass() 类中添加ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"src/applicationContext.xml"});来加载配置文件,注意配置文件的路径(根据自己的配置文件位置选择)。然后使用context.getBean()获取对象。

  2.   示例:
    public class testService
    {
    	public static EnterpriseinfoServiceImpl service;
    	@BeforeClass
    	public static void setUpBeforeClass() throws Exception
    	{
    		System.out.println("加载配置文件……");
    		ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"src/applicationContext.xml"});
    		System.out.println("加载配置文件成功");
    		service = (EnterpriseinfoServiceImpl) context.getBean("enterpriseinfoService"); //enterpriseinfoService为applicationContext.xml配置文件中Service类对象id值
    	}
    
    	@Test
    	public void testSave()
    	{
    		try
    		{
    			Enterpriseinfo info = new Enterpriseinfo();
    			info.setEnglishabbreviation("Myenglishname");
    			info.setEnglishfullname("myenglishfullname");
    			info.setEnterpriseabbreviation("enterpriseabbreviation");
    			info.setEnterprisefullname("enterprisefullname");
    			info.setStockcode(12434);
    			info.setId(3);
    			service.save(info);
    		} catch (Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    

    注意:该测试方法测试后数据并不会自动回滚
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值