首先,我对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();
}
}
1条答案
按热度按时间kqlmhetl1#
您的
LocationsRepository
单元测试不需要知道Locations
是如何构造的。因此,您可以编写如下代码: