Search code examples
springspring-boottestingintegration-testing

Testing problem, test order and auto increment


I'm doing integration tests in the spring. I am currently testing the controller layer and have a problem that I need help with.

I now have several functionalities like crud operations and so on.
The problem is when testing with integration tests, and it concerns the test order and auto incremet
in the test database (mysql database).

When I run test by test one by one they all work and they are successful, but when I run everything at once,
on the test class, because the execution order, there are errors in several tests.

For example, an adding test is executed first. In it, after adding, of course, I delete the item I added to the database, but this does not restart the auto increment and this represents a problem in other tests.

I solved the problem by modifying the other tests, but I don't think it's the right solution. I hope I explained nicely what the problem is. What are the possible solutions to this problem? Whether it is possible to restart the auto increment after each test or not.

If anyone has a solution to this problem and someone saved I would be grateful. Thanks.


Solution

  • Here, I'm not sure but think I've found a solution.

    I think these two ways can be used:

    One with the help of annotation @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) that reloads the application context and restarts everything but slows down the execution of tests.

    And the other way is with sql annotation @Sql(statements = "ALTER TABLE role AUTO_INCREMENT = 2")
    we call before the test method and restart the auto increment with the sql statement.

    I would like you to comment on whether this solution is good or not. Of course any advice is welcome. Thanks.