首页

基于spring-test的AbstractJUnit4SpringContextTests结合junit进行项目单元测试调试代码示例

标签:spring-test,AbstractJUnit4SpringContextTests,junit4,单元测试,junit代码示例,springframework调试     发布时间:2018-12-10   

一、前言

基于springframeworkspring-test的org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests,进行项目junit4单元测试代码调试示例,完整的spring-test依赖包及项目代码下载参考其他更多文章(包含本代码示例com.test.TestBase相关部分)。

二、代码示例

1. TestBase单元测试代码

package com.test;@b@@b@import org.junit.Test;@b@import org.springframework.beans.factory.annotation.Autowired;@b@import org.springframework.test.context.ContextConfiguration;@b@import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;@b@@b@@ContextConfiguration(locations={"classpath*:springContext.xml"})@b@public  class TestBase  extends AbstractJUnit4SpringContextTests {@b@	@b@	@Autowired@b@	public  CommonService  commonService;@b@	@b@	@Test@b@	public  void  testBean(){@b@		commonService.invoke();@b@	}@b@@b@}

2. springContext.xml

<?xml version="1.0" encoding="UTF-8"?>@b@<beans xmlns="http://www.springframework.org/schema/beans"@b@	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" @b@	xmlns:mvc="http://www.springframework.org/schema/mvc" @b@	xmlns:aop="http://www.springframework.org/schema/aop" @b@	xmlns:context="http://www.springframework.org/schema/context"@b@	xsi:schemaLocation="http://www.springframework.org/schema/beans@b@			http://www.springframework.org/schema/beans/spring-beans-4.1.xsd@b@			http://www.springframework.org/schema/context@b@			http://www.springframework.org/schema/context/spring-context-4.1.xsd">@b@@b@@b@	<context:annotation-config />@b@	@b@	<context:component-scan base-package="com"></context:component-scan>@b@ @b@@b@</beans>

3. CommonService类

package com.test;@b@@b@import org.springframework.stereotype.Service;@b@@b@@Service@b@public class CommonService {@b@	@b@	public  void  invoke(){@b@		System.out.println("invoke success!!!");@b@	}@b@@b@}

4. 运行TestBase控制台日志结果如下

十二月 13, 2018 1:41:51 上午 org.springframework.test.context.support.AbstractTestContextBootstrapper getTestExecutionListeners@b@信息: Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@1689405, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@cdf3c2, org.springframework.test.context.support.DirtiesContextTestExecutionListener@13e5454]@b@十二月 13, 2018 1:41:51 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions@b@信息: Loading XML bean definitions from URL [file:/C:/xwood_net/project/other-project/SpringMvc4/WebRoot/WEB-INF/classes/springContext.xml]@b@十二月 13, 2018 1:41:53 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh@b@信息: Refreshing org.springframework.context.support.GenericApplicationContext@12eec98: startup date [Thu Dec 13 01:41:53 CST 2018]; root of context hierarchy@b@invoke success!!!