需要导入两个包:org.springframework.test-3.0.3.RELEASE.jar和junit-4.8.1.jar ,
测试类需要继承:AbstractJUnit4SpringContextTests,同时测试方法上加上@Test
代码实例:
package com.ss.test;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.ss.bean.Product;
import com.ss.service.query.QueryService;
/**
* junit 单元测试
* @author wy
*
*/
@ContextConfiguration(locations = { "/bean.xml" })//指定spring配置文件位置
public class JunitTest extends AbstractJUnit4SpringContextTests {
@Resource
private QueryService queryService; //注入bean
@Test
public void test1() {
String keyWord = "空"
//下面的service就是访问数据库,然后返回查询结果
List<Product> products = queryService.products(keyWord);
for (Product product : products) {
System.out.println("name:" + product.getName());
}
}
}