java - 在 JUnit / Spring 测试类中使用辅助类
问题描述
我想问问你的知识。Spring Boot 应用程序包含各种映射器。这些应该被测试。要测试映射器,应读取 JSON 文件。这个 JSON 文件被加载到每个测试文件中。到目前为止,该功能已在每个测试类中实现,我想将功能外包给一个辅助类。我尝试如下:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {ObjectMapperConfig.class})
public class ResourceHelper {
/**
* Bean to de/serialize jsons.
*/
@Autowired
private ObjectMapper objectMapper;
/**
* Path to the file that will be used as input data.
*/
@Value("classpath:productInputs/soundRecording.json")
private Resource productInputInputFile;
/**
* Method to read a resource and convert it into a desired object.
*
* @param clazz Class of the desired object.
* @param <T> Type of the desired object.
* @return The desired object.
* @throws IOException Thrown if there is a problem accessing the url.
*/
public <T> T getSoundRecordingResource(final Class<T> clazz) throws IOException {
final String productClaimString = IOUtils.toString(productInputInputFile.getURL(), AppConstants.ENCODING);
return objectMapper.readValue(productClaimString, clazz);
}
}
在测试类中,我调用助手如下:
@Autowired
private ResourceHelper resourceHelper;
....
final ProductClaim productClaim = resourceHelper.getSoundRecordingResource(ProductClaim.class);
不幸的是,我收到以下错误消息:
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“a.package.path.CreditMapperTest”的bean时出错:通过字段“resourceHelper”表示不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“a.package.path.ResourceHelper”类型的合格 bean:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
你在这方面有什么经验?我通常是错的吗?
解决方案
经过几次尝试,我找到了一个可行的(如果不是完美的)解决方案。我用“@Component”替换了 ResourceHelper 的注释。我在每个想要使用 ResourceHelper 的测试类中对 ResourceHelper 和 ObjectMapper 进行上下文配置。在我看来,这不是一个好的解决方案,但至少我可以避免代码重复。如果以后有人遇到类似的问题并找到更好的解决方案,欢迎在本帖发帖。
推荐阅读
- codeception - 未执行任何测试 - 验收测试 Codeception
- github - 如何在 GitHub 工作流程中安排和 push/pull_request 事件?
- node.js - Express Knex req.query
- node.js - Firebase 功能:发送响应后如何最好地等待解除阻塞的承诺?
- list - 如何按属性从列表中过滤对象 - Kotlin
- node.js - 编译包含依赖项的打字稿节点 js 应用程序
- flutter - 是否有任何方法或包装让我在我的设备主页中显示特定的应用程序屏幕
- apache2.4 - 服务器证书不包含与 django 的服务器名称匹配的 ID
- python - Plotly 4.9.0 的 Jupyterlab 扩展安装失败
- angularjs - 更新到 Angular 10 后,如果没有“new”,就无法调用类构造函数 UpgradeComponent