使用H2 DB进行Spring Boot +集成测试[建议]

问题描述

我已经浏览了Internet,但是找不到答案或任何建议,因此在此处发布,以便从事类似用例工作的人可以回答或建议。让我们通过一个例子来了解用例。

我们有一个带有关系数据库(MySql)的spring boot服务,我们编写了大约300-400个集成测试,其中,我们在内存数据库中使用了H2 DB,在spring中使用了junit Jupiter API,并在春季进行了以下配置:

@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest(classes = Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,properties = "eureka.client.enabled:false")
@ActiveProfiles("test")
public abstract class BaseControllerIT {
    @AutoWired
    protected TestRestTemplate restTemplate;

    @BeforeAll
    public void setUp() {
        // Here few repositories are injected and some data is pre populated into H2 db
        // Its like some data which will be required by all test cases
    }
}

现在,在我们的真实集成测试类中扩展这个`BaseControllerIT`类,在模板下面看一下:
class SomeControllerClassIT extends BaseControllerIT {
   
    @Override
    @BeforeAll
    public void setUp() {
        super.setUp(); // Because function is overridden,I am not sure how this behaves hence super call,(Someday I will put different question for that)
        // Here we setup use case specific data
    }

    private ResponseEntity<SomeDto> exchangeAddImageCode() {
       AddImageRequestDto requestDto = // created the object here with values
         
       return restTemplate.exchange(requestDto,...otherParams)
    }


    @Test void shouldAddImage() {
       ResponseEntity<SomeDto> responseEntity = exchangeAddImageCode();
       
       // Assertions
    }

    @Test void shouldFetchAllImages() {
       exchangeAddImageCode();  // This will add image in databse,so that next exchange call will give results
       
       ResponseEntity<List<SomeDto>> responseListEntity = restTemplate.exchange(...params)
       
       // Assertions
    }


我们几乎在每个测试案例中都有这段代码,所以我想知道创建这样的通用方法并在许多测试方法中使用是否可行,如果没有,那么我们可能会遇到什么问题(我面临一个问题,但这将是一个单独的问题),所以人们请提出这种方法的利弊以及您在项目中的做法。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...