首页 > 解决方案 > 在 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)}

你在这方面有什么经验?我通常是错的吗?

标签: javaspring-bootunit-testingjunit5

解决方案


经过几次尝试,我找到了一个可行的(如果不是完美的)解决方案。我用“@Component”替换了 ResourceHelper 的注释。我在每个想要使用 ResourceHelper 的测试类中对 ResourceHelper 和 ObjectMapper 进行上下文配置。在我看来,这不是一个好的解决方案,但至少我可以避免代码重复。如果以后有人遇到类似的问题并找到更好的解决方案,欢迎在本帖发帖。


推荐阅读