【发布时间】:2020-01-29 13:55:37
【问题描述】:
我想请教您的知识。 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)}
您在这方面有什么经验?我一般都错了吗?
【问题讨论】:
-
这可能是个愚蠢的问题,但您为什么不将重复的代码位移动到一个抽象超类中,然后您的所有测试类都扩展它?
标签: java spring-boot unit-testing junit5