Когда я вызываю преобразователь модели Entity в метод преобразования DTO, я всегда получаю исключение с нулевым указателем.
Это служба преобразователя для преобразования dto в сущность и наоборот DTO ранее, и это первый раз, когда я использую DTO, и мне также нужно знать, это лучший способ, которым я реализовал службу конвертера DTO, или есть ли какие-либо предложения.
@Autowired
private ModelMapper modelMapper;
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
@Override
public NotificationDto entityToDtoNotification(Notification notification) {
ModelMapper mapper = new ModelMapper();
return mapper.map(notification, NotificationDto.class);
}
@Override
public Notification dtoToEntityNotification(NotificationDto notificationDto) {
ModelMapper mapper = new ModelMapper();
return mapper.map(notificationDto, Notification.class);
}
Когда я вызываю метод при тестовых вызовах я получаю нулевое значение
class NotificationServiceImplTest {
@Autowired
private NotificationServiceImpl notificationService;
@MockBean
private NotificationRepository notificationRepository;
@Autowired
ConverterServiceImpl converterService;
@Test
public void testCreateTicket() {
Notification notification = new Notification();
notification.setId(1);
notification.setMessage("Hello Hashan");
NotificationDto notificationDto = new NotificationDto();
//I get the null value as return
notificationDto=converterService.entityToDtoNotification(notification);
Mockito.when(notificationRepository.save(notification)).thenReturn(notification);
assertThat(notificationService.save(notificationDto)).isEqualTo(notification);
converterService.entityToDtoNotification(notification);
}
}
Notification Entity
@Entity
@Table(name = "notification")
public class Notification {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Notification() {
}
public Notification(int id, String message) {
this.id = id;
this.message = message;
}
}
Notification DTO
public class NotificationDto {
private int id;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public NotificationDto(int id, String message) {
this.id = id;
this.message = message;
}
public NotificationDto() {
}
}