[英]How to test Service class methods which uses Mapstruct mappers in Springboot?
[英]Mapstruct with uses does not instantiate class
我有以下映射器:
@Mapper(componentModel="spring", uses = {DrugstoreService.class})
public abstract class PreregisteredPharmacistMapper {
@Mapping(source = "drugstoreId", target = "drugstore")
public abstract PreregisteredPharmacist toEntity (
PreregisteredPharmacistDTO preregisteredPharmacistDTO
);
public abstract void toEntityUpdate (
@MappingTarget PreregisteredPharmacist preregisteredPharmacist,
PreregisteredPharmacistDTO preregisteredPharmacistDTO
);
public abstract PreregisteredPharmacistDTO toDTO(
PreregisteredPharmacist preregisteredPharmacist
);
}
DrugstoreService 是一个具有以下实现的接口:
@Service
public class DrugstoreServiceImpl implements DrugstoreService {
private DrugstoreRepository drugstoreRepository;
/**
* DrugstoreServiceImpl constructor.
*
* @param drugstoreRepository
*/
@Autowired
public DrugstoreServiceImpl (
DrugstoreRepository drugstoreRepository
) {
this.drugstoreRepository = drugstoreRepository;
}
@Override
public Drugstore findEntityById(Integer id) {
Optional<Drugstore> drugstore = drugstoreRepository.findById(id);
if (!drugstore.isPresent()) {
throw new ResourceNotFoundException("Drugstore", "id", id);
}
return drugstore.get();
}
}
尝试使用映射器时,会引发 NullPointerException,因为 DrugstoreService 未在映射器的实现中实例化。 这是调试代码的屏幕截图: 生成映射器的实现。 那么为什么是drugstoreService null?
当使用不同于默认的componentModel
时,您必须使用适当的依赖注入框架来实例化您的映射器。 在您的情况下,您必须使用 Spring 来获取您的映射器,而不是手动实例化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.