【问题标题】:Unit testing a Get request in a spring project在 Spring 项目中对 Get 请求进行单元测试
【发布时间】:2020-07-21 05:57:18
【问题描述】:

我开发了一个应用程序,它通过控制台从用户那里获取详细信息,并将数据存储在 Mongo 数据库中。保存数据后,使用 spring api 将数据传递到角度前端。数据被传递到前端,没有任何错误。现在我需要对返回书籍列表的方法进行单元测试。

@RestController
@RequestMapping("/api")
public class Controller {

@Autowired
    BookRepository bookRepo;

@GetMapping("/books")
    public List<Book> getBooks(){
        return bookRepo.findAll();
    }
}

BookRepository 类与 MongoRepository 一起扩展。

到目前为止我写的单元测试。

    class BookControllerTest {

    private Controller controller;

    private BookRepository repository;

    @Test
    public void getBooksTest(){

        Book b1 = new Book("12345","James","male");
        Book b2 = new Book("67890","Vicky","Female");

        List<Book> bookList = new ArrayList<>();
        bookList.add(b1);
        bookList.add(b2);
        System.out.println(bookList);

        repository.save(b1);
        repository.save(b2);
        List<Book> newList = controller.getBooks();
        System.out.println(newList);

        assertEquals(bookList,newList);
    }

}

尝试将数据保存到存储库时获得 java.lang.NullPointerException,我认为数组列表 'newList' 也是 null。

请帮我解决这个问题如何测试这个方法。

【问题讨论】:

标签: java spring unit-testing junit


【解决方案1】:

由于您正在调用 getAll the books,因此您不需要先将任何图书添加到存储库,而是可以使用 Mocking 来模拟对存储库的调用。

@Mock
private BookRepository repository;

@Test
public void getBooksTest(){

    Book b1 = new Book("12345","James","male");
    Book b2 = new Book("67890","Vicky","Female");

    List<Book> bookList = new ArrayList<>();
    bookList.add(b1);
    bookList.add(b2);
    System.out.println(bookList);

    when(repository.findAll()).thenReturn(bookList);
    List<Book> newList = controller.getBooks();
    System.out.println(newList);

    assertEquals(2,newList.size());
}

【讨论】:

  • 它仍然从行'when(repository.findAll()).thenReturn(bookList); '
【解决方案2】:

您可以为此使用@WebMvcTest(Controller.class)。此注释将确保您获得一个 Spring 上下文,其中包括测试 Web 层所需的所有 bean。此外,它会自动配置一个MockMvc 实例,您可以使用它来访问端点。

您的 Controller 类的任何其他依赖项都应该被模拟。

@WebMvcTest
// @RunWith(SpringRunner.class) required if you are using JUnit 4
public class PublicControllerJUnit4Test {

  @Autowired
  private MockMvc mockMvc;
   
  @MockBean
  private BookRepository bookRepository;

  @Test
  public void testMe() throws Exception {

    Book b1 = new Book("12345","James","male");
    Book b2 = new Book("67890","Vicky","Female");

    when(bookRepository.findAll()).thenReturn(List.of(b1, b2));

    this.mockMvc
      .perform(get("/api/books"))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$", hasSize(2)))
       .andExpect(jsonPath("$[0].isbn", is("12345")));
  }

}

使用JsonPath,您可以验证 HTTP 响应的正文。

您可以关注Testing Guide from Spring了解更多信息。

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2018-03-13
    • 2013-06-10
    • 2010-12-26
    • 2016-12-25
    • 2023-03-20
    • 1970-01-01
    • 2014-03-15
    相关资源
    最近更新 更多