[英]Spring boot test: @Sql annotation Unable to locate sql files placed in src/test/resources
[英]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.