Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Spring关闭测试数据库_Java_Spring_Testing_Spring Data - Fatal编程技术网

Java 使用Spring关闭测试数据库

Java 使用Spring关闭测试数据库,java,spring,testing,spring-data,Java,Spring,Testing,Spring Data,我需要在数据库(连接,关闭数据库…)错误期间对应用程序行为进行Spring测试。 有没有办法从Spring单元测试中关闭/终止或启动内存中的H2 db?当使用H2测试数据库运行Junit测试时,数据库实例将在测试套件开始运行时启动,并在测试完成时停止(假设您已使用bean配置了数据库) 如果您使用的是spring boot,则可以配置h2测试数据库,如下所示: src/test/resources/application-test.yml: spring: datasource: d

我需要在数据库(连接,关闭数据库…)错误期间对应用程序行为进行Spring测试。
有没有办法从Spring单元测试中关闭/终止或启动内存中的H2 db?

当使用H2测试数据库运行Junit测试时,数据库实例将在测试套件开始运行时启动,并在测试完成时停止(假设您已使用bean配置了数据库)

如果您使用的是spring boot,则可以配置h2测试数据库,如下所示:

src/test/resources/application-test.yml:

spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:testdb
    username: sa
    password:
并将您的测试配置为:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = "test")
public class SignupControllerTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Autowired
    private RealityKeeperRepository myrepo;
如果您使用的是常规spring,则可以使用
@Profile(“test”)
注释配置数据源bean:

@Bean
@Profile("test")
public DataSource devDataSource() {
    return new EmbeddedDatabaseBuilder()
        .setType(EmbeddedDatabaseType.HSQL)
        .build();
}
并将您的测试配置为:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
@ActiveProfiles(profiles = "test")
public class MyTest {
    @Autowired
    ...

您的AppConfig类应该用@Configuration注释,并包含上面提到的devDataSource bean。

是的,如果您有H2依赖项并且没有设置,那么Spring boot将为您启动嵌入式H2 DB


这篇文章应该很有用:

如果测试DB连接,这里很旧,但仍然很好。您还应该能够使用TestContainers,以便更简单地创建数据库

如果您只需要测试某些特定操作(例如存储库保存)上的某些失败,您可以简单地模拟存储库以进行测试运行:

var mockedBean = Mockito.mock(MyRepository.class);
var originalBean = ReflectionTestUtils.getField(articleService, fieldName);
Mockito.when(mockedBean.save(Mockito.any(MyEntity.class))).thenThrow(new RuntimeException("My test exception"));
ReflectionTestUtils.setField(myService, fieldName, mockedBean);
...
// test here
...
// set bean back for other test cases
ReflectionTestUtils.setField(myService, fieldName, originalBean);

谢谢,但在本文中,我没有找到如何停止和启动db来运行单元测试。Spring会自动为您执行此操作