我可以以某种方式测试我的数据库(使用的HSQL)是否正确连接? 有没有可能模拟这种数据库,只是测试它,而不是完全连接到它?
application.properties
spring.datasource.driver-class-name=org.hsqldb.jdbcDriver
spring.datasource.url = jdbc:hsqldb:file:testdb.script
spring.datasource.username=sa
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
答案 0 :(得分:0)
为什么不使用JUnit?示例代码和以下步骤 - 可能存在语法错误。
将H2内存数据库配置为测试的数据源:示例文件
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
Spring Boot将使用这些属性自动配置DataSource bean。
您可以使用Spring JPA定义测试实体和存储库(如果需要,可以在maven中包含依赖关系)
@Entity
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String value;
// add constructors, getters, setters etc
}
创建存储库
public interface TestEntityRepository
extends JpaRepository<GenericEntity, Long> { }
现在编写一个测试类来查看连接是否一切正常?
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {
@Autowired
private TestEntityRepository testEntityRepository;
@Test
public void givenTestEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
TestEntity TestEntity= testEntityRepository
.save(new TestEntity ("test"));
TestEntity foundEntity = genericEntityRepository
.findOne(genericEntity.getId());
assertNotNull(testEntity);
assertEquals(testEntity.getValue(), foundEntity.getValue());
}
}
答案 1 :(得分:0)
您可以尝试使用:
spring.datasource.testOnBorrow=true
spring.datasource.validationQuery=SELECT 1
或
spring.datasource.tomcat.testOnBorrow=true
spring.datasource.tomcat.validationQuery=SELECT 1