1.测试需要的包
<!-- 测试需要的包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13-beta-2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
2.用ClassPathXmlApplicationContext
对象写的测试类
public class TestService {
@Test
public void testQueryAll(){
System.out.println("start");
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
EmpService empService = (EmpService) applicationContext.getBean("empService");
System.out.println(empService.getClass());
List<Emp> emps = empService.queryAll();
for (Emp emp : emps) {
System.out.println(emp);
}
System.out.println("end");
}
}
3.前2步情况足够使用了,但是为了代码美观,用@RunWith
和@ContextConfiguration
两个注解建一个TestBean
类,然后测试类继承这个类。
好处:代码美观
/*
* 用@RunWith和@ContextConfiguration两个注解建一个TestBean类
* */
package com.baizhi.my.test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)// 随着工厂环境的运行
@ContextConfiguration("classpath:spring.xml")// 需要指定配置文件
public abstract class TestBean {
}
/*
* 用测试类继承TestBean这个类
* */
package com.baizhi.my.service;
import com.baizhi.my.entity.Emp;
import com.baizhi.my.test.TestBean;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
public class TestEmpService extends TestBean {
@Autowired
EmpService empService;
@Test
public void selectAllEmps() {
List<Emp> empList = new ArrayList<>();
empList = empService.selectAllEmps();
for (Emp emp : empList) {
System.out.println(emp);
}
}
}
试了一下,还行