我正在使用 MapStruct 将数据库实体转换为不可变模型对象。所以 Immutable 对象没有设置器,但 Mapstruct 在映射对象时需要设置器。所以我使用不可变对象构建器创建了一个显式构建器来提供给 Mapstruct。以下是代码片段:
@Value.Immutable
@Value.Style(overshadowImplementation = true)
public interface CarModel {
@Nullable String getCarId();
}
@Mapper(uses = ImmutablesBuilderFactory.class)
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
@Mapping(source = "id", target = "carId")
ImmutableCarModel.Builder toModel(CarEntity carEntity);
}
public class ImmutablesBuilderFactory {
public ImmutableCarModel.Builder createCarModelBuilder() {
return ImmutableCarModel.builder();
}
}
以下代码由 Mapstruct 生成:
public class CarMapperImpl implements CarMapper {
@Autowired
private final ImmutablesBuilderFactory immutablesBuilderFactory
@Override
public Builder toModel(CarEntity carEntity) {
if ( carEntity == null ) {
return null;
}
Builder builder = immutablesBuilderFactory.createCarModelBuilder();
if ( carEntity.getId() != null ) {
builder.carId( carEntity.getId() );
}
return builder;
}
}
我能够将实体转换为不可变模型对象,但单元测试为此失败。CarMapper.INSTANCE.toModel(carEntity).build();
在单元测试中调用时,它在 CarMapperImpl 类的代码下方抛出 NPE
Builder builder = immutablesBuilderFactory.createCarModelBuilder();
有谁知道这里出了什么问题?