在集成测试中使用Autowire进行数据库测试

时间:2020-01-03 03:21:57

标签: java spring-boot cucumber integration-testing autowired

我是数据库测试的新手,我正在尝试通过在类级别使用标记@SpringBootTest并通过使用Autowire来连接数据库,这并没有创建总是为null的实例化

@SprintBootTest
 Class  Test{
@Autowire
     DatabaseService databaseService;

}

有人可以建议吗?如果有人这样做类似,请给我说明

1 个答案:

答案 0 :(得分:1)

有多种测试数据库的方法,以下是其中几种,

使用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/resources复制到test/resources目录。您的测试课程与上述方法相同。但是请确保从pom中排除了h2-dependency

请也浏览这些教程