最近有点小闲,顺便研究一下spring2.5的注释ioc和就jUnit4的组合来写测试用例,发现非常方便
spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="testService" class="cn.lik.airTycoon.JunitTestServiceImpl">
</bean>
</beans>
service:
package cn.lik.airTycoon;
public class JunitTestServiceImpl {
public JunitTestServiceImpl() {
System.out.println("....init....");
}
public boolean isReal(boolean is) {
return !is;
}
}
测试用例1, 用的注释注入,这个注释注入是可以被继承的,也就是说写个抽象 类,配置好配置文件就可以了,其他测试用例继承这个就好
package test.airTycoon;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.lik.airTycoon.JunitTestServiceImpl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class AirtyCoonTest {
@Autowired
private JunitTestServiceImpl testService;
@Test
public void test() {
Assert.assertTrue(testService.isReal(false));
}
public JunitTestServiceImpl getTestService() {
return testService;
}
public void setTestService(JunitTestServiceImpl testService) {
this.testService = testService;
}
}
用例2 这个就没有写spring 的配置文件以及运行类,直接继承过来
package test.airTycoon;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import cn.lik.airTycoon.JunitTestServiceImpl;
public class AirtyCoonTest2 extends AirtyCoonTest {
@Autowired
private JunitTestServiceImpl testService;
@Test
public void test() {
Assert.assertTrue(testService.isReal(false));
}
}
联合测试: 需要测试的类追加在后面就可以。
package test.airTycoon;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ // test List
AirtyCoonTest.class, //
AirtyCoonTest2.class //
})
public class AllTests {
}
相当的方便阿,而且eclipse原生就是支持jUnit了,加上spring还有对junit的支持类,可以做到测试用例结束以后自动回滚数据库数据,完全不用担心由于测试而形成的垃圾数据