Model Mapper получает исключение нулевого указателя при вызове метода в тестовом классе - PullRequest
0 голосов
/ 09 июля 2020

Когда я вызываю преобразователь модели 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() {
    }
}

Ответы [ 2 ]

1 голос
/ 09 июля 2020

Вы должны аннотировать свой тест с помощью @RunWith(SpringRunner.class), чтобы вы могли автоматически связать атрибуты с использованием контекста Spring.

См.: https://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/html/boot-features-testing.html

0 голосов
/ 09 июля 2020

Решение: после того, как я добавил аннотацию @SpringBootTest в тестовый класс, я смог получить доступ к значению из службы конвертера без исключения нулевого указателя

@SpringBootTest
class NotificationServiceImplTest {
...