首页 > 解决方案 > 如何在春季启动测试中打印@sql注释中脚本文件的完整路径

问题描述

在多模块项目中,我想确保 Spring 的 @sql 注释使用正确的资源。有没有办法以某种方式将这些文件的完整路径记录到控制台?Spring 在执行之前会记录脚本文件名,但在不同模块的测试中,这些文件名有时是相同的。

标签: javaspring-bootspring-test

解决方案


SqlScriptsTestExecutionListener- 负责处理@Sql,第一步可以通过添加属性更改为调试相关日志logging.level.org.springframework.test.context.jdbc=debug,但调试消息不完整,如果不够,您应该创建自己的TestExecutionListener并在测试类上声明@TestExecutionListeners(listeners = SqlScriptsCustomTestExecutionListener.class) ,例如:

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));
        }
    }

这只是一个简单的例子,它可以工作。我复制的大部分源代码SqlScriptsTestExecutionListener只是为了解释。它只是@Sql在方法级别注释的情况下实现,不包括类级别。我希望它会对你有所帮助。


推荐阅读