1

Service class :

    @Value("classpath:multipleHearingLocations.json")
        public static Resource resource;
    
    
    public void someMethod(){
    
       ConcurrentHashMap<String,List<String>> multipleHearingLocations = new Objec`enter code here`tMapper().readValue(Files.newInputStream(Paths.get(**resource.getURI()**)), new TypeReference<ConcurrentHashMap<String, List<String>>>(){});
    
    }
    
    someTest.json - resided in my main/resources folder
    
    While testing in Jusint5, test class
    
    @Value("classpath:multipleHearingLocations.json")
        public static Resource resource;

But when I test it - the service calss throws a null pointer exception saying resource is null.

Test Method :

   @Mock
       public static Resource resource;
       enter code here
   
    @Test
       void getMultipleHearingLocations_shouldReturnCorrespondingMultipleEpimsIdForVenue() throws IOException {
           SscsCaseData caseData = SscsCaseData.builder()
               .appeal(Appeal.builder()
                           .hearingOptions(HearingOptions.builder().build())
                           .build())
               .processingVenue(PROCESSING_VENUE_1)
               .build();
   
   //        = new ClassPathResource("multipleHearingLocationsTest.json");
           given(venueService.getEpimsIdForVenue(caseData.getProcessingVenue())).willReturn(Optional.of("443014"));
           given(referenceDataServiceHolder.getVenueService()).willReturn(venueService);
           given(**resource.getURI()**).willReturn(new ClassPathResource("multipleHearingLocationsTest.json").getURI());
           List<HearingLocation> result = HearingsDetailsMapping.getHearingLocations(
               caseData,
               referenceDataServiceHolder
           );

What is it that I am doing wrong? Or is there a way to inject the Resource in the tests as well, so that it is available as a bean when the service class is called? Tried running it as below, still no luck

    RunWith(SpringRunner.class)
    @SpringBootTest
    @ContextConfiguration(classes = HearingsDetailsMapping.class)
    @TestPropertySource(locations = "classpath:multipleHearingLocationsTest.json")

Any help will be appreciated :)

Javad Kargar
  • 1,275
  • 1
  • 12
  • 27

1 Answers1

0

I've encounter the same problem. This injection method works fine with JUnit 4 but not with Junit5.

@RunsWith is a JUnit 4 annotation the JUnit 5 equivalent is @ExtendWith(SpringExtension.class) see this answer for more details.

To inject a resource in JUnit 5 you could use this working soulution

or

File getFile(String fileLocation) {
    return new File(this
        .getClass()
        .getClassLoader()
        .getResource(fileLocation)
        .getFile());
  }

String filelocation = "multipleHearingLocations.json" //(no "class:" before path) 

Path to multipleHearingLocations.json while testing: src/test/resources/multipleHearingLocations.json