spring整合junit集成测试
程序员文章站
2022-05-24 11:30:18
...
之前测试代码:
之前测试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了。而且可以再写个抽象类,加上上面两句注解,谁要测试直接继承这个类就行了,非常方便。
上一篇: spring整合junit集成测试
推荐阅读
-
spring集成mybatis原理(spring和mybatis整合步骤)
-
spring boot2.0.4集成druid,用jmeter并发测试工具调用接口,druid查看监控的结果
-
spring集成mybatis原理(spring和mybatis整合步骤)
-
Spring+Junit4进行接口测试实例代码
-
Spring之junit测试集成
-
详解Spring Boot Junit单元测试
-
Spring注解AOP及单元测试junit(6)
-
Spring Boot通过Junit实现单元测试过程解析
-
SSM框架整合之junit测试的方法
-
基于JUnit测试Spring MVC的正确方法。(仅限Spring 3.2)