在“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就可以跑出结果。