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配置文件加载到其中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值