簡體   English   中英

如何在spring boot test的@sql注釋中打印腳本文件的完整路徑

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

在多模塊項目中,我想確保 Spring 的 @sql 注釋使用正確的資源。 有沒有辦法以某種方式將這些文件的完整路徑記錄到控制台? Spring 在執行之前會記錄腳本文件名,但在不同模塊的測試中,這些文件名有時是相同的。

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注釋的情況下實現,不包括類級別。 我希望它會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM