1.Spring整合Junit

①导入依赖

  1. <!-- junit -->
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <version>4.12</version>
  6. </dependency>
  7. <!-- spring整合junit的依赖 -->
  8. <dependency>
  9. <groupId>org.springframework</groupId>
  10. <artifactId>spring-test</artifactId>
  11. <version>5.1.9.RELEASE</version>
  12. </dependency>

② 编写测试类

在测试类上加上
@RunWith(SpringJUnit4ClassRunner.class)注解,指定让测试运行于Spring环境
@ContextConfiguration注解,指定Spring容器创建需要的配置文件或者配置类(比如applicationContext)

@RunWith(SpringJUnit4ClassRunner.class)//让测试运行与Spring测试环境
@ContextConfiguration(locations = "classpath:配置文件1.xml")//设置Spring配置文件或者配置类
//@ContextConfiguration(classes = SpringConfig.class)
public class SpringTest {}

③注入对象进行测试

在测试类中注入要测试的对象,定义测试方法,在其中使用要测试的对象。

@RunWith(SpringJUnit4ClassRunner.class)//让测试运行与Spring测试环境
@ContextConfiguration(locations = "classpath:配置文件1.xml")//设置Spring配置文件或者配置类
//@ContextConfiguration(classes = SpringConfig.class)
public class SpringTest {

    // 想测哪个对象,就注入哪个对象
    @Autowired
    private UserService userService;

    //定义测试方法
    @Test
    public void testUserService() {
        userService.findById(10);
    }

}