spring boot & tk mapper Junit - Gukie/learning GitHub Wiki
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServiceConfig.class)
@TestPropertySource(locations = "classpath:datasource-test.properties", properties = {"a=109"})
public class ServiceTest {
@Autowired
private SysEntityService sysEntityService;
@Test
public void testIsExists(){
SysEntityCs sysEntityCs = new SysEntityCs();
boolean isExist = sysEntityService.isExists(sysEntityCs);
Assert.isTrue(isExist,"not exists");
}
}
@Configuration
@Import({ MybatisTestConfig.class})
public class ServiceConfig {
@Bean
public SysEntityService sysEntityService(){
return new SysEntityServiceImpl();
}
}
@Configuration
@TestPropertySource("classpath:config/mybatis-config.properties")
@ComponentScan("com.lokia.demo.dal")
@Import({DataSourceConfig.class,MapperAutoConfiguration.class}) // MapperAutoConfiguration很重要,否则会找不到 实体对应的table
@Slf4j
public class MybatisTestConfig {
public MybatisTestConfig(){
log.info("MybatisTestConfig loaded...");
}
}
@Configuration
@EnableConfigurationProperties(TestDataSourceProperty.class)
public class DataSourceConfig {
@Autowired
private TestDataSourceProperty dataSourceProperty;
@Bean
public DataSource dataSource(){
return DataSourceBuilder.create().type(DriverManagerDataSource.class).driverClassName(dataSourceProperty.getDriverClassName())
.url(dataSourceProperty.getUrl())
.username(dataSourceProperty.getUsername())
.password(dataSourceProperty.getPassword()).build();
}
@Bean
public SqlSessionFactory sessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
return sqlSessionFactoryBean.getObject();
}
}
@ConfigurationProperties(prefix = "datasource-test")
@Data
public class TestDataSourceProperty {
private String driverClassName;
private String url;
private String username;
private String password;
}
datasource-test.properties:
datasource-test.driver-class-name=com.mysql.jdbc.Driver
datasource-test.url=xxxx
datasource-test.username=aaaa
datasource-test.password=bbbb