[横書きアイテム]そんなREST APIで大丈夫ですか?本格的なREST APIの実装:イベントとイベントDTO

15710 ワード

イベントモデルテストの実装


テストするケースは次のとおりです.
  • Buildは正しいですか?
  • Buildの定価は
  • です.
  • DTOからモデルに変換した場合、
  • は正しく作成されますか?
    package com.carrykim.restapi.event;
    
    import com.carrykim.restapi.event.model.Event;
    import com.carrykim.restapi.event.model.dto.EventDto;
    import org.junit.jupiter.api.Test;
    import static org.junit.jupiter.api.Assertions.assertEquals;
    import static org.junit.jupiter.api.Assertions.assertNotNull;
    
    class EventTest {
        @Test
        public void build(){
            Event event = Event.builder().build();
            assertNotNull(event);
        }
    
        @Test
        public void javaBean(){
            //Given
            String eventName = "My Event";
            String eventDescription = "This is my event";
    
            //When
            Event event = Event.builder()
                    .name(eventName)
                    .description(eventDescription)
                    .build();
    
            //Then
            assertEquals(eventName, event.getName());
            assertEquals(eventDescription, event.getDescription());
        }
    
        @Test
        public void fromDto(){
            //Given
            String eventName = "My Event";
            String eventDescription = "This is my event";
    
            Event event = Event.builder()
                    .name(eventName)
                    .description(eventDescription)
                    .build();
    
            EventDto eventDto = EventDto.builder()
                    .name(eventName)
                    .description(eventDescription)
                    .build();
    
            //When
            Event fromDto = eventDto.toModel();
    
            //Then
            assertEquals(event.getName(), fromDto.getName());
            assertEquals(event.getDescription(), fromDto.getDescription());
        }
    }

    イベントモデルの実装

    package com.carrykim.restapi.event.model;
    
    import lombok.*;
    
    import javax.persistence.*;
    
    @Getter @Setter
    @EqualsAndHashCode(of = "id") @Builder
    @NoArgsConstructor @AllArgsConstructor
    @Entity
    public class Event {
        @Id @GeneratedValue
        private Integer id;
        private String name;
        private String description;
    }
    

    実装イベントDTO

    package com.carrykim.restapi.event.model.dto;
    
    import com.carrykim.restapi.event.model.Event;
    import lombok.*;
    
    @Getter @Setter @Builder
    @NoArgsConstructor @AllArgsConstructor
    public class EventDto {
        private String name;
        private String description;
    
        public Event toModel(){
            return Event.builder()
                    .name(this.name)
                    .description(this.description)
                    .build();
        }
    }