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

时间:2020-08-20 14:45:06

标签: h2 junit5 spring-boot-test spring-boot-jpa

我已经浏览了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
    }


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

0 个答案:

没有答案