1

When I'm running my SpringBootTests (using gradle) I have noticed that Test 3 always runs first. I would like understand how gradle decides the order of tests and I would like to be able to control the order and have Test 1 run first. I know that JUnit5 allows this, however I'm interested to hear whether a similar feature exists for SpringBootTests.

Thank you!

@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");

2
  • 2
    What platform are you using for running the tests? If you are using JUnit, then there is no reason why you could not use the @SpringBootTest annotation together with the @TestMethodOrder annotation. Commented Nov 26, 2020 at 21:51
  • Thanks for your comment. You're right, I needed to upgrade my Junit5 version to 5.4.0 and it worked Commented Nov 27, 2020 at 10:30

1 Answer 1

4

Thanks @vox for your comment!

I was able to run the tests in order using the @TestMethodOrder annotation. The reason it didn't work the first time round was my Junit5 version, I had to update it to 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");

Now they are running in the correct order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.