【发布时间】:2019-03-19 07:52:33
【问题描述】:
我正在使用 Mysql DB 开发一个 SPringBoot+Hibernate+REST 项目。我想知道如何对下面的课程进行单元测试。有人告诉我,Mocking 是最好的方法。我认为这与数据库模拟测试有关。即使在网上研究了很多之后,我也不知道。有人可以指导我如何测试它。如果我的项目中有使用这些数据库连接的 DAO 类,我还需要测试下面的类吗?我什至有需要测试的 RestController 类。请指导我应该如何进行。我是初学者。
DBConfiguration.Java
package com.youtube.project.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
@PropertySource(value = { "classpath:application.properties" })
@Configuration
@EnableTransactionManagement
public class DBConfiguration {
@Value("${jdbc.driverClassName}")
private String driverClass;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${hibernate.dialect}")
private String dialect;
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(url,username,password);
dataSource.setDriverClassName(driverClass);
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(getDataSource());
factory.setHibernateProperties(hibernateProperties());
factory.setPackagesToScan(new String[] {"com.youtube.project"});
return factory;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", dialect);
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory factory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(factory);
return transactionManager;
}
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(getDataSource());
em.setPackagesToScan(new String[] { "com.youtube.project.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
return em;
}
}
【问题讨论】:
标签: spring unit-testing spring-boot mocking mockito