Spring 4.x使用Junit4进行单元测试

最近公司使用Spring框架开发,以前用的不多,开始使用了之后,想写个单元测试来测试一下功能,于是乎从网上找了一下测试的例子,看到最多的就是使用

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"xxxxx"})

这种类型的,需要添加Spring专门的test用的jar包,于是乎照搬试了一下,基本功能可以跑,但是写起来太不方便了,原谅我,本人是一个必须换麻烦的人,能用最简单的方式完成的就绝不使用复杂的方式来实现,于是乎咨询了一下公司其他同事的使用方式,其实如此简单。代码实现如下:

public class DemoTest {
	private static Logger logger = Logger.getLogger(DemoTest.class);
	private ClassPathXmlApplicationContext appContext;
	private AlphaUserDao alphaUserDao;//程序内部定义的bean

	@Before
	// 在测试之前需要调用的方法,主要在测试钱启动基本的配置
	public void before() {
		logger.info("this is before method!!!");
		// 获得Spring上下文
		appContext = new ClassPathXmlApplicationContext("classpath*:META-INF/spring/*.xml");
		// 从Spring上下文中获取需要的bean
		alphaUserDao = (AlphaUserDao) appContext.getBean("alphaUserDao");
		
	}

	@Test
	public void test1() {// 测试的方法,可以写多个,如果要单独运行此方法,鼠标放在方法上Run as,然后选择Junit test即可
		logger.info("this is test method!!!");
		logger.info(alphaUserDao.queryByUserCode("xxxxx").toString());
	}

	@After
	public void after() {
		logger.info("this is after method!!!");
	}

}


特别注意Spring上下文的初始化中,配置文件的地址一定要使用以下方式类型配置
appContext = new ClassPathXmlApplicationContext("classpath*:xxx/*.xml");

即classpath后跟上*这样才能将其他第三方jar包中的Spring配置文件加载到其中。

猜你喜欢

转载自comven-eye.iteye.com/blog/2216013