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

标签 java spring-boot unit-testing junit5

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

相关文章:

java - Jackson 无法反序列化日期

java - Java 中套接字的 BufferedReader.readLine() 卡住了

java - 具有大量参数的 HTTP.GET 操作 Spring Rest

java - 如何使用 @JsonAlias 注释将嵌套值映射到属性?

angularjs - 超时在 AngularJS Karma 中不起作用 - Jasmine 测试

java - 单元测试所有集合不能为空的通用方法

python - 如何用任何参数填充函数?

java - 如何检查字符串池内容?

java - 对多个应用程序使用同一个 session

java - Spring Boot自定义滚动日志文件