Spring itself is a container in which all business objects are managed through the spring container. Spring's injection features ease the coupling of classes to classes. However, it also gives us a lot of trouble writing unit tests, but this happens only if the unit test tools provided by spring are not taken into account.
1. Prepare the required jar packs.
Need to prepare Spring-mock.jar and Naming-factory-dbcp.jar. The first jar package includes the Unit Test tool class provided by spring, and the second jar package is the class that provides the necessary to establish a JDBC connection.
2. Inherit abstracttransactionaldatasourcespringcontexttests.
Spring offers several JUnit-based unit test tool classes, which only introduce abstracttransactionaldatasourcespringcontexttests, and others see official documentation. This is a unit test case with a transaction, you can set whether the database transaction is committed or rolled back after the unit test succeeds, and the default is rollback.
The Getconfiglocations method needs to be implemented in the inheriting class, primarily to get the Application-context.xml file of spring.
protected String[] getConfigLocations() {
String[] config = new String[] {
"xxx-applicationContext.xml", "xxxx-applicationContext.xml"
};
return config;
}
Note that first, if you use the above notation, these XML files must be under Classpath; second, TransactionManager can only define one.
3. Write your own test cases.
The sample code is as follows:
public abstract class MyDependencyInjectionSpringContextTests
extends AbstractTransactionalDataSourceSpringContextTests {
protected ServiceContext context;
public MyDependencyInjectionSpringContextTests() {
}
/**
* 重写父类的onSetUpBeforeTransaction方法
**/
protected void onSetUpBeforeTransaction() throws Exception {
super.onSetUpBeforeTransaction();
//此处可以加入你想进行的统一操作
......
//调用子类的处理
beforeSetUp();
}
protected abstract void beforeSetUp() throws Exception;
protected String[] getConfigLocations() {
String[] config = new String[] {
"service-applicationContext.xml", "dao-applicationContext.xml"
};
return config;
}
}
====================================================================
public class MockServiceTest
extends MyDependencyInjectionSpringContextTests {
Mock mock;
MockService service;
protected void beforeSetUp() throws Exception {
//初始化测试需要使用的数据
mock=new Mock();
mock.setName("test");
mock.setType(1);
service=(MockService) applicationContext.getBean("mockService");
}
public void testAddMock() {
//测试方法
service.addMock(mock);
//这里使用的是是hibernate,增加后主键被填充,所以只要判断实体对象的id是否为null即可
Assert.assertTrue("测试addMock方法失败。" mock.getMockId!=null);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MockServiceTest.class);
}
}