1、使用说明
为了简化JUnit测试、使用Spring框架也可以整合测试
2、导入依赖
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- jdbc模板 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
</dependencies>
3、在测试类添加注解
修改测试类TestFindAnno.java
@RunWith注解:这个是指定使用的单元测试执行类,这里就指定的是SpringJUnit4ClassRunner.class;
@ContextConfiguration注解:这个指定spring配置文件所在的路径,可以同时指定多个文件
在该类上添加@RunWith和@ContextConfiguration两个注解。我们需要测试的是UserService,
在TestFindAnno中声明一个UserService的属性,并在该属性上添加@Autowired注解,为该属性注入值。修改后的TestFindAnno如下:
@RunWith(SpringJUnit4ClassRunner.class)//指定采用spring的运行器来执行单元测试方法
@ContextConfiguration("classpath:applicationContext.xml")//指定sprign配置文件的路径
public class TestIOC {
@Autowired
private UserService userService;//要测试的目标,直接注入进来
/**
* 测试注解
*/
@Test
public void test1() {
userService.saveUser();
}
}
4、在纯注解的工程使用单元测试
@RunWith注解:这个是指定使用的单元测试执行类,这里就指定的是SpringJUnit4ClassRunner.class;
@ContextConfiguration注解:这个指定spring配置文件所在的路径,可以同时指定多个文件
//测试类TestFindAnno.java
package com.day02Jdbc.test;
import com.day02Jdbc.config.SpringConfig;
import com.day02Jdbc.domain.Customer;
import com.day02Jdbc.service.CustomerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
* @ Author :ShaoWei Sun.
* @ Date :Created in 9:44 2018/11/10
*/
@RunWith(SpringJUnit4ClassRunner.class)//指定采用spring的运行器来执行单元测试方法
@ContextConfiguration(classes = SpringConfig.class)//指定spring配置文件的路径
public class TestFindAnno {
@Autowired
private CustomerService customerService;
@Test
public void test2() {
List<Customer> list = customerService.findAllCustomer();
for (Customer customer : list) {
System.out.println(customer);
}
}
// @Test
// public void test1() {
// ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
// CustomerService customerService = (CustomerService) ac.getBean("customerService");
// List<Customer> list = customerService.findAllCustomer();
// for (Customer customer : list) {
// System.out.println("customer = " + customer);
// }
// }
}
-