简体   繁体   中英

MockHttpServletResponse is not returning mocked list

I'm trying to test a simple controller mocking the service results. For that I'm using when().thenReturn() method of Mockito returning a new array. It does work for asserting the OK status and the returning array size, the problem is that the objects inside that array are empty, so I can't assert them to have some value.

Specifically the MockHttpServletResponse response body is [{},{},{}] and the assertion error java.lang.AssertionError: No value at JSON path "$[0].id" .

This is a really basic case, but I will need to do some transformations at the returning array from the service, so I need their values to be mocked in order to test them.

Is it possible to mock them? What am I doing wrong? Thanks.

Here is the code for the test:

@ExtendWith(SpringExtension.class)
@WebMvcTest(BookController.class)
public class BookControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private BookService bookService;

    @Test
    void getAllBooks() throws Exception {
        List<Book> books = new ArrayList<>();
        books.add(new Book(1L, "Book 1", "Author 1", "Description 1"));
        books.add(new Book(2L, "Book 2", "Author 2", "Description 2"));
        books.add(new Book(3L, "Book 3", "Author 3", "Description 3"));
        when(bookService.getAllBooks()).thenReturn(books);

        mockMvc.perform(MockMvcRequestBuilders.get(Urls.BOOK_URL)
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(3)))
                .andExpect(jsonPath("$[0].id").value(1L));
    }
}

The actual controller:

@RestController
@RequestMapping(Urls.BOOK_URL)
public class BookController {

    private final BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping
    public List<Book> getAllBooks() {
        return bookService.getAllBooks();
    }

}

And the basic entity:

@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private String description;
}

It actually does return your list, which is apparent by the assertion of size 3 not failing. The problem is your Book class doesn't have getters and setters and those (or at least the getters) are needed to create JSON.

As you are using Lombok add @Getters and @Setters to the class to generate those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM