- 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()获取对象。
- 示例:
- 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();
- }
- }
- }
注意:该测试方法测试后数据并不会自动回滚
使用JUnit4对SSH2框架Service/Dao层进行单元测试
最新推荐文章于 2021-02-16 05:36:43 发布