Search code examples
javaspring-bootjunit

Wrtiing unit test for a repository which uses a JSON as datasource


First of all, I am pretty new to JAVA. I would like to write a unit test for my repository which uses a JSON data source as you can see below. I don't know how can I fill locations in my test. When I checked injected locations in locationRepository instance, I see that it is null. Does anybody know what is the best way to write a unit test for that scenario?

@Slf4j
@Component
@RequiredArgsConstructor
public class LocationRepository {

    private final Locations locations;

    //Some methods which make query against to locations
    public Optional<Location> findLocationById(id String)
    {
        //...
    }
 }



@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@Data
@DynamicConfigurationProperties(value = "./data/locations.json")
public class Locations {
    public List<Location> locations;
}


@RunWith(MockitoJUnitRunner.class)
public class LocationRepositoryTest {

    @InjectMocks
    LocationRepository locationRepository;

    @Test
    public void it_should_returns_location_when_google_api_returned_null() {
        //given
        String locationId = "1";
        //when
        Optional<Location> location = locationRepository.findLocation(locationId);
        //then
        assertThat(location).isNotEmpty();
    }
}

Solution

  • Your LocationsRepository unit tests do not need to know about how Locations is constructed. So you can write something like:

    @RunWith(MockitoJUnitRunner.class)
    public class LocationRepositoryTest {
        
        @InjectMocks
        LocationRepository locationRepository;
    
        @Mock
        Locations locations;
    
        @Test
        public void it_should_returns_location_when_google_api_returned_null() {
            //given
            String locationId = "1";
            Location location1 = new Location();  // ID = 1
            Location location2 = new Location(); // ID = 2
            //when
            when(locations.getLocations()).thenReturn(List.of(location1, location2));
            Optional<Location> location = locationRepository.findLocation(locationId);
            //then
            assertThat(location).contains(location1);
        }
    }