有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java单元测试spring项目中的Get请求

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

@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);
    }

}

爪哇语。lang.NullPointerException是在尝试将数据保存到存储库时获得的,我认为数组列表“newList”也为null

请帮助我解决如何测试此方法的问题


共 (2) 个答案

  1. # 1 楼答案

    由于要调用getAll 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());
    }
    
  2. # 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了解更多信息