首页 > 解决方案 > 在集成测试中使用 Autowire 进行数据库测试

问题描述

我是数据库测试的新手,我正在尝试通过在类级别使用标签 @SpringBootTest 并使用 Autowire 来连接数据库,它不会创建始终为空的实例化

@SprintBootTest
 Class  Test{
@Autowire
     DatabaseService databaseService;

}

有人可以建议吗?如果有人做过类似的事情,请给我指导

标签: javaspring-bootcucumberintegration-testingautowired

解决方案


有多种方法可以测试您的数据库,这里有几种方法,

使用内存数据库(例如:H2)使用test范围

使用 h2(in-memory-DB) 来模拟数据库非常好。虽然这不是强制性的,我们也可以使用mockito来模拟数据库交互。

添加这些依赖项,

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.196</version>
    <scope>test</scope>
</dependency>

现在你的测试类应该是这样的,

@RunWith(SpringRunner.class)
@SpringBootTest(classes = YourApp.class, webEnvironment = RANDOM_PORT)
Class  DatabaseServiceTest{

    @Autowired
    private DatabaseService databaseService;
}

复制实际的数据库配置属性

首先,您需要将您的 properties/yml 从目录复制main/resourcestest/resources目录。您的测试类与上述方法中给出的相同。但请确保你h2-dependency从你的 pom.xml 中排除了。

请同时探索这些教程


推荐阅读