前言
下面提供如何使用spring的AbstractJUnit4SpringContextTests来获取已注入到spring的对象进行测试单元
代码示例
1.spring测试单元基类,示例代码如下
import org.springframework.test.context.ContextConfiguration;@b@import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;@b@@b@@ContextConfiguration(locations={"classpath*:applicationContext-*.xml"})@b@public abstract class TestBase extends AbstractJUnit4SpringContextTests {@b@}
2.用户测试用例类(通过区域服务查询关键词"上海市"的区域信息编码),示例代码如下:
import org.junit.Test;@b@import org.springframework.beans.factory.annotation.Autowired;@b@ @b@import com.xx.Region; @b@import com.xx.IRegionXService; @b@import com.xx.TestBase;@b@@b@public class RegionServiceTest extends TestBase {@b@ @b@ @Autowired@b@ IRegionXService service; @b@ @b@ @Test@b@ public void regionTest(){@b@ Region area= service.getByName("上海市");@b@ System.out.println(area.getCode()); @b@ }@b@ @b@ @Test@b@ @Ignore@b@ public void regionTest2() throws InterruptedException {@b@ Region area= service.getByName("江苏省");@b@ System.out.println(area.getCode()); @b@ }@b@ @b@ @b@}