Java新手求教:如何为JSON数据源的LocationRepository编写单元测试
针对JSON数据源的LocationRepository单元测试方案
你的问题根源是测试中没有初始化Locations实例,导致LocationRepository依赖的locations字段为null。下面给出三种适配不同场景的最优方案:
方案一:Mock隔离依赖(纯单元测试推荐)
单元测试核心是验证LocationRepository的业务逻辑,无需依赖真实JSON文件。用Mockito mockLocations对象,手动构造测试数据,完全隔离外部依赖。
@RunWith(MockitoJUnitRunner.class) public class LocationRepositoryTest { @InjectMocks private LocationRepository locationRepository; @Mock private Locations locations; // Mock依赖对象 @Before public void setUp() { // 构造测试用的Location列表 List<Location> testLocations = Arrays.asList( new Location("1", "北京"), new Location("2", "上海") ); // 配置Mock对象返回测试数据 when(locations.getLocations()).thenReturn(testLocations); } @Test public void it_should_return_location_when_id_exists() { // given String locationId = "1"; // when Optional<Location> location = locationRepository.findLocationById(locationId); // then assertThat(location).isNotEmpty(); assertThat(location.get().getId()).isEqualTo("1"); } @Test public void it_should_return_empty_when_id_not_exists() { // given String locationId = "3"; // when Optional<Location> location = locationRepository.findLocationById(locationId); // then assertThat(location).isEmpty(); } }
优势:测试速度快,可精准控制输入数据,覆盖所有边界场景(存在/不存在的ID、空列表等),完全聚焦Repository本身的逻辑。
方案二:加载真实JSON数据(数据源验证推荐)
如果需要验证Repository与真实JSON数据源的交互逻辑,可使用Jackson手动读取测试用JSON文件,初始化Locations实例。
@RunWith(MockitoJUnitRunner.class) public class LocationRepositoryTest { private LocationRepository locationRepository; private Locations locations; @Before public void setUp() throws IOException { // 用Jackson解析JSON文件(将测试用JSON放在src/test/resources/data/下) ObjectMapper objectMapper = new ObjectMapper(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream("data/locations.json"); locations = objectMapper.readValue(inputStream, Locations.class); // 直接构造Repository实例(利用@RequiredArgsConstructor) locationRepository = new LocationRepository(locations); } @Test public void it_should_return_location_from_real_json() { String locationId = "1"; Optional<Location> location = locationRepository.findLocationById(locationId); assertThat(location).isNotEmpty(); } }
优势:验证真实JSON数据格式是否符合预期,确保Repository逻辑与实际数据源匹配,适合做集成前的数据源验证。
方案三:Spring上下文加载(Spring集成测试推荐)
如果是Spring Boot项目,可通过Spring Test上下文自动加载配置,让框架处理@DynamicConfigurationProperties注解的JSON加载逻辑。
@SpringBootTest public class LocationRepositoryTest { @Autowired private LocationRepository locationRepository; @Test public void it_should_return_location_from_spring_loaded_config() { String locationId = "1"; Optional<Location> location = locationRepository.findLocationById(locationId); assertThat(location).isNotEmpty(); } }
优势:完整模拟生产环境的Bean注入和配置加载流程,适合验证整个组件链的协同工作,缺点是测试启动速度较慢。
方案选择建议
- 仅测试Repository业务逻辑:选方案一(Mock隔离)
- 验证真实JSON数据源逻辑:选方案二(手动加载JSON)
- 验证Spring环境下的完整流程:选方案三(Spring上下文加载)
内容的提问来源于stack exchange,提问作者leo
相关产品推荐
相关产品推荐

