junit 为使用JSON作为数据源的存储库编写单元测试

xn1cxnb4  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(121)

首先,我对JAVA还很陌生。我想为我的仓库写一个单元测试,它使用JSON数据源,如下图所示。我不知道如何在我的测试中填充位置。当我检查locationRepository示例中的注入位置时,我发现它是空的。有人知道为这种情况写单元测试的最好方法吗?

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

kqlmhetl1#

您的LocationsRepository单元测试不需要知道Locations是如何构造的。因此,您可以编写如下代码:

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

相关问题