MINU
MINU

Reputation: 1

Handling Null ID in Spring Boot JPA Entity when Writing Spring REST Docs Tests

I'm currently working with Spring Boot and JPA, and I'm using the @Builder pattern for my entity classes. For my primary key field id, I'm using @Id and @GeneratedValue(strategy = GenerationType.IDENTITY) annotations. Since the ID is auto-generated, I intentionally did not include the id field in the constructor used by the Builder pattern.

However, I'm facing an issue when writing tests for Spring REST Docs. Since I cannot set the id value when creating entities, the id appears as null in my REST Docs output. For example, when creating a entity(Webtoon)

This is the constructor

@Builder
    public Webtoon(String title, String summary, String originalImageName, String imagePath,
        PublishDay publishDay, Platform platform,String author) {
        this.title = title;
        this.summary = summary;
        this.originalImageName = originalImageName;
        this.imagePath = imagePath;
        this.publishDay = publishDay;
        this.platform = platform;
        this.author = author;
    }

and this is the test code

   webtoon1 = Webtoon.builder()
            .title("w1 title")
            .summary("w1 summary")
            .originalImageName("w1 imgName")
            .imagePath("w1 imgPath")
            .publishDay(PublishDay.THURSDAY)
            .platform(Platform.NAVER)
            .author("w1 author")
            .build();
// webtoon2,webtoon3

@Test
public void testWebtoonList() throws Exception {
    List<WebtoonResponse> mockWebtoonResponses = List.of(
        new WebtoonResponse(webtoon1),
        new WebtoonResponse(webtoon2),
        new WebtoonResponse(webtoon3)
    );

    Mockito.when(webtoonService.findWebtoonList()).thenReturn(mockWebtoonResponses);

    mockMvc.perform(get(uri))
        .andExpect(status().isOk())
        .andDo(document("get-v1-get-webtoons",
            responseFields(
                fieldWithPath("[].id").description("Webtoon ID"),
                // other fields
            )
        ));
}

In the REST Docs, the id field is returned as null. How should I handle this situation to properly document the id field in my REST Docs?

enter image description here

I looked for a few solutions.

Including the id field in the constructor: I could simply add the id field to my entity's constructor used by the Builder pattern.

Creating a constructor specifically for test cases: Another option is to create a separate constructor that includes the id field, which would be used only in test scenarios.

Using Java Reflection: I could also consider using Java Reflection to forcibly create an instance of the entity with the id field set.

However, all these solutions involve modifying the entity structure just for the sake of testing, which I'm hesitant about. What would be the best practice in this situation to ensure that my REST Docs accurately reflect the id field without compromising the integrity of my entity design?


Here are my Controller, Service, and DTO classes for reference

@RequiredArgsConstructor
@RequestMapping("/api/v1/webtoon")
@RestController
public class WebtoonApiController {
 @GetMapping
    public ResponseEntity<List<WebtoonResponse>> getWebtoonList() {
        List<WebtoonResponse> webtoonList = webtoonService.findWebtoonList();
        return ResponseEntity.ok(webtoonList);
    }
}
@RequiredArgsConstructor
@Service
public class WebtoonService {
 @Transactional(readOnly = true)
    public List<WebtoonResponse> findWebtoonList() {
        List<Webtoon> webtoons = webtoonRepository.findAll();
        return webtoons.stream()
            .map(WebtoonResponse::new)
            .toList();
    }
}

@Getter public class WebtoonResponse {

private final Long id;
private final String title;
private final String summary;
private final String originalImageName;
private final String imagePath;
private final PublishDay publishDay;
private final Platform platform;
private final String author;

public WebtoonResponse(Webtoon webtoon) {
    this.id = webtoon.getId();
    this.title = webtoon.getTitle();
    this.summary = webtoon.getSummary();
    this.originalImageName = webtoon.getOriginalImageName();
    this.imagePath = webtoon.getImagePath();
    this.publishDay = webtoon.getPublishDay();
    this.platform = webtoon.getPlatform();
    this.author = webtoon.getAuthor();
}

}

I wrote RestDocs test code for the API documentation. But the entity constructor doesn't have an ID. So in the RestDocs documentation, the ID value comes out as a null value. Should I change the entity class for the test code?

Upvotes: 0

Views: 86

Answers (0)

Related Questions