Spring整合Junit(零配置)
Spring-Test整合Junit还可以使用纯注解
的方式。
一、导入Spring-Test和Junit4的相关jar包
spring-test-4.3.3.RELEASE.jar
junit-4.12.jar
hamcrest-core-1.3.jar
二、编写Bean类
CustomerDao接口:
package com.yiidian.dao;
/**
*
* @author http://www.yiidian.com
*
*/
public interface CustomerDao {
public void save();
}
CustomerDaoImpl实现:
package com.yiidian.dao.impl;
import org.springframework.stereotype.Component;
import com.yiidian.dao.CustomerDao;
/**
* @author http://www.yiidian.com
*
*/
@Component(value="customerDao")
public class CustomerDaoImpl implements CustomerDao {
@Override
public void save() {
System.out.println("测试Spring整合Junit用法");
}
}
无需编写applicationContext.xml文件
三、编写Spring-Test整合Junit的测试类(重点在这里)
package com.yiidian.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.yiidian.dao.CustomerDao;
/**
* @author http://www.yiidian.com
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SpringConfig.class) //关键在这里,换成了配置类
public class Demo1 {
//使用@Resource或者@Autowired进行注入
@Resource
private CustomerDao customerDao;
@Test
public void test1(){
//不需要像以前这样加载spring配置了!
/*ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerDao customerDao = (CustomerDao)ac.getBean("customerDao"); */
customerDao.save();
}
}
主要是:@ContextConfiguration("classpath:applicationContext.xml")
改为@ContextConfiguration(classes=SpringConfig.class)
四、运行测试
热门文章
优秀文章