JUnit测试断言期望[null]实际返回null该如何修复
问题背景
业务规则要求:实体数据更新预处理阶段,若other_companies字段为空则直接删除该字段,非空则保留。
编写单元测试验证逻辑时,预期预处理后other_companies字段值为[null](包含一个null元素的列表),实际运行后该字段取值为null,断言失败。
测试用例代码
@Test public void shouldRemoveOtherCompaniesOnUpdatePreProcessing(){ List<BaseEntity> baseEntities = new ArrayList<>(); BaseEntity baseEntity = new ContactEntity(); Map<String, Object> data = new HashMap<>(); data.put("first_name", "Sample"); data.put("last_name", "Contact"); data.put("email", "sample.contact@gmail.com"); data.put("id", 12345); data.put("company_id", 1234); List<Map<String, Object>> secondaryCompaniesWithNotRemove = new ArrayList<>(); Map<String, Object> secondaryCompany1 = new HashMap<>(); secondaryCompany1.put("company_id",1234L); secondaryCompaniesWithNotRemove.add(secondaryCompany1); baseEntity.setData(data); baseEntities.add(baseEntity); Map<String, Object> options = new HashMap<>(); options.put(PreferenceKeyConstants.ENTITIES_TO_SYNC, "ACCOUNTS"); when(contactEntityEndpoint.findById(baseEntity.getId().toString(),null)).thenReturn((ContactEntity) baseEntity); List<Map<String, Object>> expectedSecondaryCompaniesIsRemoved = new ArrayList<>(); expectedSecondaryCompaniesIsRemoved.add(null); contactCompanyFieldsPreProcessor.doOnUpdatePreProcessing(baseEntities, new ArrayList<>(), options); Map<String, Object> preProcessedBaseEntityData = baseEntities.get(0).getData(); assertEquals(expectedSecondaryCompaniesIsRemoved, preProcessedBaseEntityData.get("other_companies")); }
运行报错信息
java.lang.AssertionError: Expected :[null] Actual :null
问题原因
两处错误直接导致测试不通过:
- 测试数据构造缺失关键步骤:你定义了
secondaryCompaniesWithNotRemove变量但从未使用,构造的实体data map里根本不存在other_companies这个key,预处理逻辑不可能凭空生成该字段。 - 测试预期和业务规则冲突:业务规则明确说明
other_companies为空就删除字段,如果给该字段赋值为null属于标准空值场景,预处理后字段会被直接从map中移除,此时调用get("other_companies")返回null是符合删除逻辑的,和你写的预期值[null]完全矛盾。
修复方案
根据实际测试目标二选一调整即可:
- 验证「空的other_companies字段会被删除」逻辑:
- 构造测试数据时主动往data中放入
other_companies字段,赋值为null或者空列表 - 把断言改为判断map中不存在该key,示例代码:
assertFalse(preProcessedBaseEntityData.containsKey("other_companies")); - 构造测试数据时主动往data中放入
- 验证「other_companies包含null元素时会被保留」逻辑:
- 构造测试数据时主动往data中放入
other_companies字段,值为你预期的[null]列表 - 调整预处理逻辑的空判断规则:仅当字段值本身为null、或者列表长度为0时才判定为空删除字段,不要把「列表内包含null元素」判定为空场景。
- 构造测试数据时主动往data中放入
内容的提问来源于stack exchange,提问作者Suraj Karosia
相关产品推荐
相关产品推荐

