Zmur
Zmur

Reputation: 334

How to print full path to script files in @sql annotation in spring boot test

In a multi-module project I want to be sure that Spring's @sql annotation uses correct resources. Is there a way to log full path of those files to console somehow? Spring does log script file name before execution, but in tests for different modules those file names are the same sometimes.

Upvotes: 2

Views: 1413

Answers (1)

borino
borino

Reputation: 1750

SqlScriptsTestExecutionListener - responsible for the processing of @Sql, for the first step you can change to debug related log by adding property logging.level.org.springframework.test.context.jdbc=debug, but the debug message is not fully and if is not enough you should create your own TestExecutionListener and declare on test class @TestExecutionListeners(listeners = SqlScriptsCustomTestExecutionListener.class) for example:

public class SqlScriptsCustomTestExecutionListener extends AbstractTestExecutionListener {

    @Override
    public void beforeTestMethod(TestContext testContext) {
        List<Resource> scriptResources = new ArrayList<>();
        Set<Sql> sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(testContext.getTestMethod(), Sql.class);
        for (Sql sqlAnnotation : sqlAnnotations) {
            String[] scripts = sqlAnnotation.scripts();
            scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
            scriptResources.addAll(TestContextResourceUtils.convertToResourceList(testContext.getApplicationContext(), scripts));
        }
        if (!scriptResources.isEmpty()) {

            String debugString = scriptResources.stream().map(r -> {
                try {
                    return r.getFile().getAbsolutePath();
                } catch (IOException e) {
                    System.out.println("Unable to found file resource");
                }
                return null;
            }).collect(Collectors.joining(","));

            System.out.println(String.format("Execute sql script :[%s]", debugString));
        }
    }

It is just quick example and it works. Most of source code i copied from SqlScriptsTestExecutionListener just for explanation. It is just realization in case of @Sql annotation on method level, and not included class level. I hope it will be helps you.

Upvotes: 2

Related Questions