我想请教一下您的知识。 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: Error creating bean with name 'a.package.path.CreditMapperTest': Unsatisfied dependency expressed through field 'resourceHelper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'a.package.path.ResourceHelper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
您在这方面有哪些经验?我一般都是错的吗?
最佳答案
尝试在Resource Helper上添加注解@Service。这只是我的猜测。
关于java - 在 JUnit/Spring 测试类中使用辅助类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968605/