简体   繁体   中英

Use helper class inside JUnit / Spring test class

I would like to ask for your knowledge. A spring boot application contains various mappers. These should be tested. To test the mapper, a JSON file should be read. This JSON file is loaded in every test file. So far, the functionality has been implemented in every test class, I would like to outsource the functionality in a helper class. I try this as follows:

@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);
  }

}

And within a test class, I call the helper as follows:

  @Autowired
  private ResourceHelper resourceHelper;
  ....
  final ProductClaim productClaim = resourceHelper.getSoundRecordingResource(ProductClaim.class);

Unfortunately I get the following error message:

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)}

What experience have you had in this area? Am I generally wrong?

Try to add anotation @Service on ResourceHelper. It is only my guess.

After a few tries, I found a working, if not perfect, solution. I replaced the annotation of the ResourceHelper with "@Component". I do the context configuration of the ResourceHelper as well as the ObjectMapper in every test class that wants to use the ResourceHelper. This is not a nice solution in my opinion but at least I can avoid code duplication. If someone has a similar problem in the future and finds a better solution, he is welcome to post it in this post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM