java - Camel: Add TypeConverter in Test Case
问题描述
Hy,
I'm currently writing a TestCase in which, at some point, I need an automatic type conversion for a self written model object to String.
When executing the code "live" it works, because other components are initiated then, but in the testcase they are not, which is why I need to add the mock type convert in the test case.
This is what I did so far, but it does not seem to work, as the type conversion crashes (org.apache.camel.TypeConversionException: Error during type conversion from type: com.....MyClass to the required type: java.lang.String)
context // Autowired in the test class
.getTypeConverterRegistry().addTypeConverters(new TypeConverters() {
@Converter
public String myClassToString(MyClass file) {
if (file.getName().equals(expectedFileName)) {
return fileContent;
} else {
throw new IllegalArgumentException(
"Unknown file for Mock TypeConverter: " + file.getName());
}
}
});
I'm not sure this is the correct way of adding a type converter without creating a dedicated class, but its what I found after so research
解决方案
因此,在尝试了更多事情并真正理解了引发的异常之后,我发现,我(可能)做错了什么。
经过一些反复试验后,我将上述代码注册到类型转换器注册表中,而类型转换器本身没有任何更改(不确定我更改了什么,也许这只是一些缓存问题..)
当转换器最终被骆驼注册并执行时,我收到了这个错误:
org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“java.lang.String”类型的合格bean:预计至少有1个有资格作为自动装配候选者的bean。依赖注释:{}
似乎不可能使用匿名类(以 Spring Boot 作为运行器)添加 TypeConverter,因为 Spring 试图在那里注入一些 String。
我能够通过将 TypeConverter 提取到实际(非匿名)类,然后将该类的实例添加到注册表来解决问题。
也可以在测试中使用内部类来执行此操作,只要它是公共的。
在任何情况下,让实际的 conterter 方法是静态的很重要,否则 Spring 会抛出相同的错误。
不知道为什么会发生这一切,但至少我最终让它工作了。
也许有人可以对 Springs 的行为有所了解,它想要注入一个字符串,什么都没有,应该自动装配。
问候
克里斯
推荐阅读
- android - 使用 FlutterActivity 时如何将数据从 java 模块传输到 Flutter?
- javascript - 按下Javascript中的按钮后如何重新聚焦在文本字段中的位置?
- multithreading - 在多线程上下文中使用带有生菜的 Spring-Data-Redis 的 OutOfDirectMemoryError
- c++ - 同步 gRPC 服务器的线程/IO 模型是什么?(C++)
- mysql - 是否可以在 bulk_create() Django 上设置外键?
- python - 使用python将文件夹结构中多个文件夹中的多个pdf合并为1个PDF
- javascript - 如何找出不包含任何类的元素?
- python - 为什么 Flask 会在动态 url 到达“?”时立即停止输入?
- wkwebview - iOS 13.4.1 更新后 WKWebView 无法识别点击手势
- powershell - 通过调用变量初始化谷歌浏览器