springTest

Spring整合测试,用于测试各种方法等

Spring整合测试

  • 导入spring整合Junit的坐标

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.2.RELEASE</version>
    </dependency>
  • 在测试类上面标记注解

    package com.jwang.test;

    import com.jwang.controller.AccountController;
    import com.jwang.pojo.Account;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    import java.sql.SQLException;
    import java.util.List;

    /**
    * 包名:com.jwang.test
    *
    * @author Leevi
    * 日期2020-08-09 15:16
    * 直接在测试用例中,注入要使用的对象AccountController
    * 1. 我们自己不创建核心容器,那么我们就应该交给别人(Junit)去创建核心容器
    * 1. 引入spring整合Junit的依赖 spring-test
    * 2. 保证Junit的版本是4.12以及以上的版本
    * 3. 在单元测试类上添加RunWith注解
    * @RunWith(SpringJUnit4ClassRunner.class)
    * 4. 指定有Junit创建核心容器的时候,要加载的配置文件/配置类
    * @ContextConfiguration(locations = "classpath:applicationContext.xml") 混合开发
    * @ContextConfiguration(classes = 配置类名.class) 纯注解开发
    */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class TestSpring {
    @Autowired
    private AccountController accountController;
    @Test
    public void testFindAll() throws SQLException {
    List<Account> accountList = accountController.findAll();
    System.out.println(accountList);
    }

    @Test
    public void testFindById() throws SQLException {
    Account account = accountController.findById(1);
    System.out.println(account);
    }

    @Test
    public void testDeleteById() throws SQLException {
    accountController.deleteById(3);
    }

    @Test
    public void testAdd() throws SQLException {
    Account account = new Account();
    account.setName("ww");
    account.setMoney(1000.0);

    accountController.add(account);
    }

    @Test
    public void testUpdate() throws SQLException {
    Account account = accountController.findById(5);
    account.setName("aobama");
    account.setMoney(1500.0);

    accountController.update(account);
    }
    }