如何使用 jUnit 测试 JdbcTemplate 方法?

How test JdbcTemplate methods using jUnit?

我使用 Spring 和 JdbcTemplate 编写了简单的 java 项目。我写了 SpringConfig class ,我把我的 Postgres 数据库信息和创建 DataSource 和 JdbcTemplate beans。然后我用 Autowired class 构造函数编写了 CRUD 方法,一切都是 运行 完美但测试没有。我想使用 H2 数据库并在 test.resources 包中创建 application.properties,然后我在创建 class 构造函数并自动装配它的地方创建测试 class,以及何时尝试测试CRUD 方法我得到 ParameterResolutionException:“无法解析构造函数中的参数 [javax.sql.DataSource arg0]”。你能指出我的错误吗:

@Configuration
public class SpringConfig {

private static final String URL = "jdbc:postgresql://localhost:5432/test";
private static final String DRIVER = "org.postgresql.Driver";
private static final String USERNAME = "root";
private static final String PASSWORD = "123";

@Bean
public DataSource dataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(DRIVER);
    dataSource.setUrl(URL);
    dataSource.setUsername(USERNAME);
    dataSource.setPassword(PASSWORD);
    return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(){
    return new JdbcTemplate(dataSource());
}
@Repository
public interface SimpleDao<E> {

void create(E e);

Optional<E> read(int id);

void delete(E e);

void update(E e);

List<E> index();
}
public interface StudentDao extends SimpleDao<Student> {
}
@Component
public class SpringStudentDao implements StudentDao {
private static Logger logger = LoggerFactory.getLogger(SpringStudentDao.class);

private final JdbcTemplate jdbcTemplate;

public SpringStudentDao(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}

@Override
public void create(Student student) {
    String sql = "INSERT INTO student VALUES(?,?,?)";
    int insert = jdbcTemplate.update(sql, student.getID(), student.getName(), student.getSurname());
    if (insert == 1) {
        logger.info("New student added " + student.toString());
    }
}

@Override
public Optional<Student> read(int id) {
    String sql = "SELECT * FROM student WHERE id=?";
    Student student = null;
    try {
        student = jdbcTemplate.queryForObject(sql, new Object[]{id}, new StudentMapper());
    } catch (DataAccessException exception) {
        logger.info("Student not found " + id);
    }
    return Optional.ofNullable(student);
}

@Override
public List<Student> index() {
    String sql = "SELECT * FROM student";
    return jdbcTemplate.query(sql, new StudentMapper());
}
@DataJdbcTest
class SpringStudentDaoTest {

private JdbcTemplate jdbcTemplate;
private SpringStudentDao studentDao;


@Autowired
public SpringStudentDaoTest(DataSource dataSource){
    jdbcTemplate = new JdbcTemplate(dataSource);
    studentDao = new SpringStudentDao(jdbcTemplate);

}

@Test
public void shouldGetListOfStudents(){
    List<Student> students = studentDao.index();
    assertEquals(4, students.size());
}

为什么您尝试为嵌入式数据库构建 JdbcTemplate 而不是自动装配自动配置的数据库?

@DataJdbcTest
public class JdbcTest {

    JdbcTemplate jdbcTemplate;

    @Autowired
    JdbcTest(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Test
    public void myTest() {
    }

}

Auto-configured Data JDBC Tests

查看 @DataJdbcTest 的信息

By default, it configures an in-memory embedded database, a JdbcTemplate, and Spring Data JDBC repositories. Regular @Component beans are not loaded into the ApplicationContext.

@DataJdbcTest 自动配置的完整组件列表 - 请参阅 Appendix D. Test auto-configuration annotations

org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration

为什么你的方法失败了:

If you’re familiar with the Spring Test Framework, you may be used to using @ContextConfiguration(classes=…​) in order to specify which Spring @Configuration to load. Alternatively, you might have often used nested @Configuration classes within your test.