无法为包含更新方法的RestController执行Junit测试用例?

时间:2019-09-11 09:03:08

标签: java rest spring-boot junit mockito

在尝试为包含 update 方法的 controller 类编写 Junit Test 案例时,遇到错误了吗?

我已经为其他方法编写了 JUnit 测试用例,但是当我尝试为 update 方法运行junit测试用例时,出现了以下错误。 org.junit.ComparisonFailure:预期:<“ [{” title“:”使用JPA休眠“,”主题“:” Java“,”发布者“:” IGH出版物“,”语言“:”英语“, “ numberOfPages”:1532,“ isbn”:“ EMP_6953_2019”}]“>但为:<” []“>

LibraryController.java

@PutMapping("/books/{isbn}")
    public ResponseEntity<Book> updateBook(@PathVariable String isbn, @Valid @RequestBody Book bookDetails) {
        log.info("Entering updateBook() method ");
        Book updatedBook = librarianService.updateBook(isbn, bookDetails);
        log.info("Exiting updateBook() method ");
        return ResponseEntity.ok(updatedBook);
    }

updateBook()方法的Junit测试用例。
LibraryControllerTest.java

@Test
    public void testUpdateBook() throws Exception {

        Book book1 = new Book("EMP_6953_2019", "Hibernate", "Java", "IGH Pubications", "English", 1232);
        String isbn = book1.getISBN();
        Book bookDetails = new Book("EMP_6953_2019", "Hibernate with JPA", "Java", "IGH Pubications", "English", 1532);
        when(librarianService.updateBook(isbn, bookDetails)).thenReturn(bookDetails);

        MockHttpServletResponse response = mockMvc.perform(put("/librarian/books/{isbn}", "EMP_6953_2019")
                .contentType(MediaType.APPLICATION_JSON).content(jsonList.write(bookDetails).getJson())).andReturn()
                .getResponse();
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
        assertThat(response.getContentAsString()).isEqualTo(jsonList
                .write(new Book(bookDetails.getISBN(), bookDetails.getTitle(), bookDetails.getSubject(),
                        bookDetails.getPublisher(), bookDetails.getLanguage(), bookDetails.getNumberOfPages()))
                .getJson());

    }

预期输出:
“ {” title“:” Hibernate with JPA“,” subject“:” Java“,” publisher“:” IGH Pubications“,” language“:” English“,” numberOfPages“:1532,” isbn“:” EMP_6953_2019“ }”
实际输出:
“”

0 个答案:

没有答案