java - 如何在春季启动测试中打印@sql注释中脚本文件的完整路径
问题描述
在多模块项目中,我想确保 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
在方法级别注释的情况下实现,不包括类级别。我希望它会对你有所帮助。
推荐阅读
- c# - 我需要在“使用”中添加什么才能让我的代码运行?
- qt - 使用 CMake 配置 Eigen 3.3.7 时从 C:/Qt/5.12.4/msvc2015_64/bin/qmake.exe 发现不合适的 Qt 版本“5.12.4”
- django - 如果字符串中存在字段名,我如何使用 Django 模型过滤器从我的数据库中查询对象
- binary - 如何在 32 位二进制数之间添加空格
- c++ - 关于类和成员函数的问题
- python - 不确定为什么打印功能没有发生
- r - 更改ggplot中堆叠直方图条的顺序
- javascript - 处理双击时的第二个 mousedown 事件
- java - QueryDsl MongoDB - 访问深层嵌套对象以进行查询
- c - C标准输入因文件重定向而损坏?