我想问问你的知识。 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)}
您在这方面有什么经验?我通常错了吗?
尝试在ResourceHelper上添加注释@Service。这只是我的猜测。
经过几次尝试,我找到了一个可行的,即使不是完美的解决方案。我用“ @Component”替换了ResourceHelper的注释。我在每个要使用ResourceHelper的测试类中对ResourceHelper以及ObjectMapper进行上下文配置。我认为这不是一个很好的解决方案,但至少我可以避免代码重复。如果将来有人遇到类似的问题并找到更好的解决方案,欢迎他将其发布在这篇文章中。