之前测试代码:
之前测试service时都是先加载spring的主配置文件,然后getBean从IOC容器中得到service的实例再进行相应的测试。比较麻烦。
殊不知其实是可以在类上加两行注解:
再@Resource注入,直接就可以测试service了。而且可以再写个抽象类,加上上面两句注解,谁要测试直接继承这个类就行了,非常方便。
@Test
public void testAddOld() {
ApplicationContext appContext = new ClassPathXmlApplicationContext("application.xml");
appContext.getBean("testTbService");
TestTb testTb = new TestTb();
testTb.setName("小虫");
testTb.setBirthday(new Date());
testTbService.addTestTb(testTb);
}
之前测试service时都是先加载spring的主配置文件,然后getBean从IOC容器中得到service的实例再进行相应的测试。比较麻烦。
package cn.smallbug;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.smallbug.core.bean.TestTb;
import cn.smallbug.core.service.TestTbService;
/**
*
* @timestamp Jan 31, 2016 11:27:24 PM
* @author smallbug
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-context.xml" })
public class TestTestTb {
@Resource
private TestTbService testTbService;
@Test
public void testAdd() {
TestTb testTb = new TestTb();
testTb.setName("小虫");
testTb.setBirthday(new Date());
testTbService.addTestTb(testTb);
}
}
殊不知其实是可以在类上加两行注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-context.xml" })
再@Resource注入,直接就可以测试service了。而且可以再写个抽象类,加上上面两句注解,谁要测试直接继承这个类就行了,非常方便。