Testing in Spring Boot - Junit5

2022-11-01

  • How would I load initial data into a sql db with spring boot junit tests?

    To load initial data into a SQL database using Spring Boot and JUnit, you can use the @Sql annotation in your JUnit test class. This annotation allows you to specify the SQL scripts that should be executed before the test is run.

    Here is an example of how you can use the @Sql annotation to load initial data into a database:

    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Sql({
        "/path/to/script1.sql",
        "/path/to/script2.sql"
    })
    public class MyTest {
    
        @Test
        public void test() {
            // Test code goes here
        }
    }
    

    In this example, the SQL scripts script1.sql and script2.sql will be executed before the test method is run. This will load the initial data into the database, and the test can then be run on this data.

  • How can I inherit sql from super classes?

    You can inherit SQL scripts from superclasses by using the @SqlGroup annotation. This annotation allows you to define a group of SQL scripts that can be inherited by other test classes.

    Here is an example of how you can use the @SqlGroup annotation to define a group of SQL scripts:

    
    @SqlGroup({
        @Sql(scripts = "/path/to/script1.sql"),
        @Sql(scripts = "/path/to/script2.sql")
    })
    public @interface InitialData {
        // This class defines a group of SQL scripts that can be inherited by other test classes
    }
    
    

    To inherit the SQL scripts from the InitialData class in another test class, you can use the @InitialData annotation:

    Copy code
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @InitialData
    public class MyTest {
    
        @Test
        public void test() {
            // Test code goes here
        }
    }
    
    

    In this example, the InitialData class defines a group of SQL scripts that will be executed before the test method is run. This allows you to inherit the SQL scripts from the InitialData class in other test classes without having to duplicate the script definitions.