Spring笔记(第三弹:使用JUnit对Spring工程进行测试)

在“Spring笔记(第二弹:搭建第一个Spring工程)”中,我们在测试类中写了一个main方法,直接右键Run As->Java Application来进行测试。现在我们使用JUnit来进行测试。
引入JUnit的包
在Java Build Path里点击”Add Library”,选择JUnit,然后选择JUnit4,finish。这样就引入了JUnit的包。
然后我们把上次的Test类改个名字,我们要测试UserDao,我们就把测试类改成TestUserDAO,在要测试的方法上加上“@Test”的注解,代码如下:

package test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.demo.dao.UserDAO;

public class TestUserDAO {

    @Test
    public void testSayHello() {
        // 读取spring的容器
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 从spring容器中获取对象
        UserDAO userDao = context.getBean("userDAO", UserDAO.class);
        // 从得到的对象中调用需要的方法
        userDao.sayHello();
    }

}

这样,我们就可以右键Run As->JUnit Test来进行测试。
但是我们希望不要在测试类中手动读取spring容器,所以下面来改进一下。
引入spring的test包
我们引入spring-test-3.2.9.RELEASE.jar,这个包在spring-framework-3.2.9.RELEASE中就有。
然后在测试类的类名上方添加spring对JUnit的支持,代码如下:

@RunWith(SpringJUnit4ClassRunner.class)

再加上对spring配置文件的读取,代码如下:

@ContextConfiguration(locations = {"classpath:applicationContext.xml"})

然后就可以方便对UserDAO进行测试,完整代码如下:

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.demo.dao.UserDAO;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestUserDAO {

    @Autowired
    private UserDAO userDAO;

    @Test
    public void testSayHello() {
        userDAO.sayHello();
    }

}

右键Run As->JUnit Test就可以跑出结果。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值