带有 Spring 引导的 JUnit 5 - 如何使用不同的配置文件重复测试?

Che*_*rry 4 java spring spring-boot junit5

这是 JUnit 5 数据驱动测试的经典示例。

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@Slf4j
@ExtendWith(SpringExtension.class)
@SpringBootTest
class ScrathTest {
  @Autowired
  private MyBean myBean;

  @ParameterizedTest
  @ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE}) // six numbers
  void isOdd_ShouldReturnTrueForOddNumbers(int number) {
    myBean.doSomeThing(number)
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我需要运行的不是整数数组,而是配置文件数组呢?我的意思是我创建了一个测试,然后创建了 3 个测试配置文件,然后在每个创新中使用不同的配置文件重复该测试 3 次。是否可以?

笔记

@ActiveProfile 注释不是一个解决方案,因为它只是激活列出的配置文件,而不需要重复测试和重新创建上下文。

M.M*_*as. 5

我不认为这JUnit5提供了类似的功能。但是,您可以创建一个抽象类,派生类将指定活动配置文件。

class abstract AbstactScrathTest {

  @Autowired
  protected MyBean myBean;

  @ParameterizedTest
  @ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE}) // six numbers
  void isOdd_ShouldReturnTrueForOddNumbers(int number) {
    myBean.doSomeThing(number)
  }

}

@Slf4j
@ExtendWith(SpringExtension.class)
@SpringBootTest
@ActiveProfiles("test1")
class ScrathTestWithTestProfile1 extends AbstractScrathTest{
}


@Slf4j
@ExtendWith(SpringExtension.class)
@SpringBootTest
@ActiveProfiles("test2")
class ScrathTestWithTestProfile2 extends AbstractScrathTest{
}
Run Code Online (Sandbox Code Playgroud)