restdocs-spec
restdocs-spec copied to clipboard
Bean Validation on Nested Fields doesn't work
I'm trying to use ConstrainedFields for Bean Validation but unable to get it to work.
<restdocs-api-spec.version>0.9.9</restdocs-api-spec.version>
<restdocs-spec.version>0.18</restdocs-spec.version>
As you can see below, CreateBookRequestDto has property 'author' and it should not be null.
@Value
@Builder
public class CreateBookRequestDto {
@NotEmpty String title;
@NotNull @Valid AuthorDto author;
}
@Value
@Builder
@Validated
public class AuthorDto {
@NotEmpty String firstName;
@NotEmpty String lastName;
}
@Test
public void create() throws Exception {
//when
BookDto book = BookDto.builder().isbn("0-9705-6867-3").title("A Time To Kill").author(AuthorDto.builder().firstName("John").lastName("Grisham").build()).build();
CreateBookRequestDto createBookRequestDto = CreateBookRequestDto.builder().title("A Time To Kill").author(AuthorDto.builder().firstName("John").lastName("Grisham").build()).build();
when(bookService.create(any())).thenReturn(book);
//then
ConstrainedFields constrainedFields = new ConstrainedFields(CreateBookRequestDto.class);
mvc
.perform(post("/books")
.content(new ObjectMapper().writeValueAsBytes(createBookRequestDto))
.contentType(APPLICATION_JSON_VALUE)
.accept(APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andDo(print())
.andDo(
document(
"create-book",
resourceDetails().description("Create a book."),
requestFields(
constrainedFields.withPath("title").description("The title of the book."),
constrainedFields.withPath("author").description("The Author of the book."),
constrainedFields.withMappedPath("author.firstName", "author").description("The author's first name."),
constrainedFields.withMappedPath("author.lastName", "author").description("The author's last name.")
),
responseFields(
fieldWithPath("isbn").description("The ISBN of the book."),
fieldWithPath("title").description("The title of the book."),
fieldWithPath("author.firstName").description("The author's first name."),
fieldWithPath("author.lastName").description("The author's last name.")
)
)
);
}
Generated openapi-3.0.yml file. As you can see below, author should be required but it doesn't show up in the required fields.
components:
schemas:
books-1095758460:
required:
- title
type: object
properties:
author:
required:
- firstName
- lastName
type: object
properties:
lastName:
type: string
description: The author's last name.
firstName:
type: string
description: The author's first name.
description: The Author of the book.
title:
minLength: 1
type: string
description: The title of the book.
Is it a bug or am I missing something?
Just in case if it's a bug, I created an issue on restdocs-api-spec. [https://github.com/ePages-de/restdocs-api-spec/issues/138]