如何用JUnit4测试spring service

如何用JUnit4测试spring service,第1张

1 建立一个test的目录,在此目录下放置所有的JunitTestCase类和TestCase的配置文件

2 将项目中的Spring配置文件(默认名称为applicationContext.xml)复制到test目录下,并重新命名为JunitTestConf.xml。

3 根据Junit测试的需要修改JunitTestConf.xml文件中的内容,如数据库连接等。

4 新建一个名为SpringConfForTest.java的类,在此类中配置Spring启动所需的配置文件,并启动Spring。此类的内容如下:

package test

import org.junit.AfterClass

import org.junit.BeforeClass

import org.junit.Test

import org.springframework.context.ApplicationContext

import org.springframework.context.support.ClassPathXmlApplicationContext

import com.soma.global.WebContextHolder

public class SpringConfForTest {

@BeforeClass

public static void setUpBeforeClass() throws Exception {

//Spring启动所需要的配置参数文件,其中test/JunitTestConf.xml文件中保存了数据库连接等参数,可根据具体情况做修改

String[] paths = new String[] {"test/JunitTestConf.xml", "com/soma/conf/applicationContext-dao-hr.xml","com/soma/conf/applicationContext-dao.xml","com/soma/conf/applicationContext-dao-bug.xml","com/soma/conf/applicationContext-dao-change.xml","com/soma/conf/applicationContext-dao-common.xml","com/soma/conf/applicationContext-service-hr.xml" }

//启动Spring,得到Spring环境上下文

ApplicationContext ctx = new ClassPathXmlApplicationContext(paths)

//在此类启动时,将Spring环境上下文保存到单根类WebContextHolder中,以提供给其它的测试类使用

WebContextHolder.getInstence().setApplicationContext(ctx)

}

@AfterClass

public static void tearDownAfterClass() throws Exception {

}

@Test

public void test(){

//必须要写一个test空方法,否则SpringConfForTest类不会启动

}

}

5 新建TestSuite类,类名为AllTests,类的内容如下所示:

package test

import junit.framework.Test

import junit.framework.TestSuite

import org.junit.runner.RunWith

import org.junit.runners.Suite

import test.com.soma.domain.busilogic.hr.HrBusiLogicTest

import test.com.soma.domain.service.hr.checkOverTimeDateTest

@RunWith(Suite.class)

@Suite.SuiteClasses({

SpringConfForTest.class,

HrBusiLogicTest.class,

checkOverTimeDateTest.class

})

/**

* 批量执行Junit测试类,把类名写入到上面的Suite.SuiteClasses({})中,用逗号分隔

*/

public class AllTests {

public static Test suite() {

TestSuite suite = new TestSuite("Test for test")

//$JUnit-BEGIN$

//$JUnit-END$

return suite

}

}

注意:将SpringConfForTest.class放在第一个执行,以启动Spring配置环境,把自己的TestCase类放到后面,用逗号分开。在测试时,只要执行这个TestSuite类就可以了。

6 写自己的TestCase类,以CheckOverTimeDateTest.java为例子,文件内容如下:

public class CheckOverTimeDateTest {

private static HrTbovertimeManager hrTbovertimeManager

private static ExcuteSqlDAO excuteSqlDAO

@BeforeClass

public static void setUpBeforeClass() throws Exception {

//从Spring上下文中得到hrTbovertimeManager接口类的实例

hrTbovertimeManager=(HrTbovertimeManager)BeanUtil.getBean("hrTbovertimeManager")

excuteSqlDAO = (ExcuteSqlDAO) BeanUtil.getBean("excuteSqlDAO")

}

@Test

public void testGetProjectList()throws Exception {

List<OvertimeDetailValue>overtimeDetailValueList = new ArrayList<OvertimeDetailValue>()

int index = 9

for(int i = 1 i <= indexi++){

OvertimeDetailValue overtimeDetailValue = new OvertimeDetailValue()

overtimeDetailValue.setOtApplyDate("2009-05-0"+i)

overtimeDetailValueList.add(overtimeDetailValue)

}

String resultStr = hrTbovertimeManager.checkOverTimeDate(overtimeDetailValueList)

assertEquals("false", resultStr)

}

/**

* 导入2009-03月份出勤记录excel文件,返回null表示导入成功,需要先删除3月份的数据

*/

@Test

public void testSaveExcelDutyInformation() throws Exception{

// 在导入3月份出勤记录前先删除3月份的记录,执行delete from hr_tbdutyinformation

excuteSqlDAO.excuteSql("delete from hr_tbdutyinformation where dutydate>='2009-02-26' and dutydate<='2009-03-25'")

// System.out.println("----------"+System.getProperty("user.dir")+"/src/test/duty200903.xls")

String fileName = System.getProperty("user.dir")

+ "/src/test/duty200903.xls"

assertNull(hrTbdutyInformationManager.saveExcelDutyInformation(fileName))

}

}

说明:BeanUtil.getBean("")相当于WebContextHolder.getInstence().getApplicationContext().getBean(""),只是对此方法做了封装。

7 在Eclipse中,启动AllTests,选择逗Run As JunitTest地,即可先启动Spring环境,再依次运行你自己所写的JunitTestCase,是不是很简单哪看赶快动手试试吧。

Step 1: 写出基本的算术代码Calculate.java

package com.ysc.main

public class Calculate {

    public static int add(int a, int b) {

        return a + b

    }

    public static int minus(int a, int b) {

        return a - b

    }

    public static int divide(int a, int b) throws Exception {

        if (b == 0) {

            throw new Exception("除数不能为0")

        }

        return a / b

    }

    public static int multiply(int a, int b) {

        return a * b

    }

}

Step 2: 对Calculate类添加Junit4的测试单元,右键->new->JUnit Test Case,如下图

Step 3: 对添加的测试用例进行配置,命名为TestCalculate,点击Next

Step 4: 选择需要测试的函数,点击Finish,完成JUnit的基本配置

Step 5: 在经过上面的步骤之后,就可以得到配置好的测试用例

package com.ysc.main

import static org.junit.Assert.*

import org.junit.Before

import org.junit.BeforeClass

import org.junit.Test

public class CalculateTest {

    @BeforeClass

    public static void setUpBeforeClass() throws Exception {

    }

    @Before

    public void setUp() throws Exception {

    }

    @Test

    public void testAdd() {

        fail("Not yet implemented")

    }

    @Test

    public void testMinus() {

        fail("Not yet implemented")

    }

    @Test

    public void testDivide() {

        fail("Not yet implemented")

    }

    @Test

    public void testMultiply() {

        fail("Not yet implemented")

    }

}

Step 6: 现在需要做的就是添加上需要测试的数据

package com.ysc.main

import static org.junit.Assert.*

import org.junit.Before

import org.junit.BeforeClass

import org.junit.Test

public class CalculateTest {

    @BeforeClass

    public static void setUpBeforeClass() throws Exception {

    }

    @Before

    public void setUp() throws Exception {

    }

    @Test

    public void testAdd() {

        assertEquals(5, Calculate.add(1, 4))

    }

    @Test

    public void testMinus() {

        assertEquals(-1, Calculate.minus(2, 3))

    }

    @Test

    public void testDivide() throws Exception {

        assertEquals(0, Calculate.divide(1, 4))

    }

    @Test

    public void testMultiply() {

        assertEquals(4, Calculate.multiply(1, 4))

    }

}

Step 7: 开始进行测试,右键->Run as->JUnit Test

在使用junit前, 我们需要 了解 一些规则,如何去写好一个测试类。

之所以放在junit前说明,是因为单元测试不一定只能用junit去做,就算我们什么软件依赖都不用,也是可以做的,就是会麻烦点,不要下意识的觉得 单元测试=Junit ,应该是 单元测试 >Junit

市面上单元测试并不是只有junit一家的,还有许多其他的框架模块,只是相比之下它们没有junit普及。而且有些公司还有内部的单元测试框架,也未必是基于junit开发的。

甚至必要的时候,哪怕不用Juint,也要进行单元测试,这就只能用Java原生的断言语句等等了。

1)java中断言(assert)的使用

一开始我以为断言是junit中的特色,其实不然,断言是一个编程术语,常用于单元测试中,甚至它都并不只存在于java。

java中的断言 ,是在JDK1.4后开始使用的,关键字是assert,它主要是用在代码 开发和测试时期 ,用于对某些数据进行预期判断,如果结果不符合自己的预期,程序就警告或退出。

它的语法大概如下:

语法①:assert condition

condition代表一个布尔类型的条件表达式,如果为真,就继续正常运行,如果为假,则异常退出

这里我断言x>=0,如果计算结果符合我的预期则无事发生,如果计算结果x小于0,则不符合我的预期,断言失败,抛出AssertionError。

语法②:assert condition : message

condition和上面是一样的,冒号后的message通常用于断言失败后的异常提示信息,它就是个传入到AssertionError构造参数里的值,用于我们自定义错误详情的,这里就不放代码了,大家可以自己试试。

关于使用断言还有个最重要的规则: 程序的任何行为都不能依赖断言,千万不要把断言当成程序中的逻辑来使用 ,也就是你的代码即便删除里面所有的断言语句,它的逻辑和之前也是不能有任何变化的。因为它只是用于测试和开发的,甚至JVM默认都是关闭断言使用的,如果没有开启断言,程序会自动忽略所有断言语句,仿佛它们并不存在,要执行assert语句,必须给Java虚拟机传递-enableassertions(可简写为**-ea**)参数 启用断言 ,也可以使用-disenableassertion(简写为**-da) 参数 关闭断言**(默认就是关闭的)。

最后,虽然java有提供断言,但我们实际开发中却很少使用它,因为如果要使用它去测试,还不如直接用Junit框架去写单元测试的代码,Junit也提供了断言的语句。

虽然我们用不上java里的断言,但是也要有所了解,并且大部分的断言其实逻辑都是差不多的。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9987059.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-04
下一篇2023-05-04

发表评论

登录后才能评论

评论列表(0条)

    保存