gpt4 book ai didi

java - 在 JUnit/Spring 测试类中使用辅助类

转载 作者:行者123 更新时间:2023-12-01 18:39:28 25 4
gpt4 key购买 nike

我想请教一下您的知识。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com