我有这个实体 -
public class MerchantConfig {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long merchantId;
private String configKey;
private String configValue;
..
}
它目前在商家级别存储配置(键和值)。
我们现在也需要在用户级别(用户到商家的一对多映射)存储配置。
我们将这两列添加到实体中 -
private Long entityId;
private String entityType;
entityId 现在将存储merchantId/UserId,entityType 将与字符串值“merchantid”或“user_id”指示相同。
这是一个现有的服务层方法 -
public MerchantConfig enableSync(boolean isActive, Long merchantId,boolean isSync){
MerchantConfig merchantConfig= merchantConfigRespository.findByMerchantIdAndConfigKey(merchantId,Constants.MerchantConfigKeys.SYNC_ENABLED.key);
if(merchantConfig==null){
merchantConfig = new MerchantConfig();
merchantConfig.setMerchantId(merchantId);
merchantConfig.setConfigKey(Constants.MerchantConfigKeys.SYNC_ENABLED.key);
}
if(isSync)
merchantConfig.setConfigValue("1");
else
merchantConfig.setConfigValue("0");
merchantConfig.setIsActive(isActive);
return merchantConfigRespository.save(merchantConfig);
}
这是它上面的控制器 -
@PostMapping("/admin/enableSync")
public ResponseEntity<Object> enableSync(HttpServletRequest request, HttpServletResponse response,
@RequestParam("merchantId") Long merchantId,
@RequestParam("isValid") boolean isValid,
@RequestParam("isSync") boolean isSync) {
if (isValid && isSync)
LOGGER.info("enabling sync for merchant {}", merchantId);
else
LOGGER.info("disabling sync for merchant {}", merchantId);
MerchantConfig merchantConfig = merchantConfigService.enableSync(isValid, merchantId, isSync);
if(merchantConfig!=null)
return new ResponseEntity<>(new ResponseDTO(Constants.API_RESPONSE_SUCCESS, merchantConfig, "success"),
HttpStatus.OK);
return new ResponseEntity<>(new ResponseDTO(Constants.API_RESPONSE_FAILURE, "unable to enable sync"),
HttpStatus.OK);
}
我们决定只改变服务和向下,保持控制器层不变。
用服务方法中的 findByEntityIdAndEntityTypeAndConfigKey() 替换存储库方法调用 findByMerchantIdAndConfigKey() 并进行此更改 -
public MerchantConfig enableSync(boolean isActive, Long merchantId,boolean isSync){
MerchantConfig merchantConfig= merchantConfigRespository.findByEntityIdAndEntityTypeAndConfigKey(merchantId,Enum.MerchantConfigType.MERCHANT_ID.v,Constants.MerchantConfigKeys.SYNC_ENABLED.key);
if(merchantConfig==null){
merchantConfig = new MerchantConfig();
merchantConfig.setEntityId(merchantId);
merchantConfig.setEntityType(Enum.MerchantConfigType.MERCHANT_ID.v);
merchantConfig.setConfigKey(Constants.MerchantConfigKeys.SYNC_ENABLED.key);
}
if(isSync)
merchantConfig.setConfigValue("1");
else
merchantConfig.setConfigValue("0");
merchantConfig.setIsActive(isActive);
return merchantConfigRespository.save(merchantConfig);
}
我在服务层放了什么有用的单元测试用例?
如果我要模拟存储库层响应并验证 servive 方法是否返回与模拟响应相同的 MerchantConfig 实体,这不是矫枉过正吗?
相反,我觉得测试 db 值会更有用,方法是在 db 中创建一些已知条目。例如,在这种情况下,当 db 中已经有一些商家级别的配置并且要输入用户级别的配置时,应该覆盖用户级别的条目,因为配置器正在尝试取消设置所有商家级别的配置。
如果在 db 中给定商家级别的配置,测试会很有用,当调用 save config API 端点来保存用户级别的配置时,商家级别的配置被标记为非活动状态。
顺便问一下,这些测试叫什么?请给出一些解决方案,因为我已经在这场辩论中苦苦挣扎了一段时间。每次坐下来写传统的单元测试用例,我都花太多时间,还是有问题,这是单元测试无法覆盖的。请提供一些全面的指南来编写此类测试。