使用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.   示例:
    [java]  view plain  copy
    1. public class testService  
    2. {  
    3.     public static EnterpriseinfoServiceImpl service;  
    4.     @BeforeClass  
    5.     public static void setUpBeforeClass() throws Exception  
    6.     {  
    7.         System.out.println("加载配置文件……");  
    8.         ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"src/applicationContext.xml"});  
    9.         System.out.println("加载配置文件成功");  
    10.         service = (EnterpriseinfoServiceImpl) context.getBean("enterpriseinfoService"); //enterpriseinfoService为applicationContext.xml配置文件中Service类对象id值  
    11.     }  
    12.   
    13.     @Test  
    14.     public void testSave()  
    15.     {  
    16.         try  
    17.         {  
    18.             Enterpriseinfo info = new Enterpriseinfo();  
    19.             info.setEnglishabbreviation("Myenglishname");  
    20.             info.setEnglishfullname("myenglishfullname");  
    21.             info.setEnterpriseabbreviation("enterpriseabbreviation");  
    22.             info.setEnterprisefullname("enterprisefullname");  
    23.             info.setStockcode(12434);  
    24.             info.setId(3);  
    25.             service.save(info);  
    26.         } catch (Exception e)  
    27.         {  
    28.             e.printStackTrace();  
    29.         }  
    30.     }  
    31. }  

    注意:该测试方法测试后数据并不会自动回滚
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值