【问题标题】:Use helper class inside JUnit / Spring test class在 JUnit / Spring 测试类中使用辅助类
【发布时间】: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


【解决方案1】:

尝试在 ResourceHelper 上添加注解 @Service。这只是我的猜测。

【讨论】:

  • 感谢您的回答,不幸的是,错误消息仍然存在。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2022-01-04
    • 2018-11-02
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多