【问题标题】:Can I run SpringBootTests in a specific order?我可以按特定顺序运行 SpringBootTests 吗?
【发布时间】:2020-11-26 21:32:27
【问题描述】:

当我运行我的 SpringBootTests(使用 gradle)时,我注意到测试 3 总是首先运行。我想了解 gradle 如何决定测试的顺序,并且我希望能够控制顺序并首先运行测试 1。 我知道 JUnit5 允许这样做,但是我很想知道 SpringBootTests 是否存在类似的功能。

谢谢!

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    TestRestTemplate restTemplate;


    @Test
    void returnSomething1() {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/hello",
                String.class)).contains("hello");

    @Test
    void returnSomething2() {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/yo",
                String.class)).contains("yo");


    @Test
    void returnSomething3() {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/bye",
                String.class)).contains("bye");

【问题讨论】:

  • 您使用什么平台来运行测试?如果您使用的是 JUnit,那么您没有理由不能将 @SpringBootTest 注释与 @TestMethodOrder 注释一起使用。
  • 感谢您的评论。你说得对,我需要将我的 Junit5 版本升级到 5.4.0 并且它可以工作

标签: spring-boot spring-boot-test


【解决方案1】:

感谢@vox 的评论!

我能够使用@TestMethodOrder 注释按顺序运行测试。 第一次不成功的原因是我的Junit5版本,我不得不将它更新到5.4.0。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    TestRestTemplate restTemplate;


    @Test
    @Order(1)
    void returnSomething1() {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/hello",
                String.class)).contains("hello");

    @Test
    @Order(2)
    void returnSomething2() {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/yo",
                String.class)).contains("yo");


    @Test
    @Order(3)
    void returnSomething3() {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/bye",
                String.class)).contains("bye");

现在它们以正确的顺序运行。

【讨论】:

    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多