如何将身份验证添加到控制器测试弹簧中?

发布于 2025-02-11 00:42:36 字数 2645 浏览 0 评论 0原文

我在应用程序中的春季应用中添加了一个基本验证。

  #Security
  security:
    user:
      name: admin
      password: admin

我还添加了Spring-boot-Starter-Security使其正常工作。现在,我很好奇我如何需要重构控制器测试,就像我实现基本AUTH后所有这些测试返回401状态之后一样。我正在使用Junit5和Mockito。这是ControlerTests类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = BooksApplication.class)
@AutoConfigureMockMvc
class BookControllerTests {
@Autowired
MockMvc mockMvc;

@Autowired
ObjectMapper mapper;
@MockBean
BookController bookController;

@Autowired
private BookConverter converter;

@Test
public void createBook_success() throws Exception {
    Book book = Book.builder().name("Great book").author("Ivan")
            .pagesNumber(340).publisher("New Publisher").build();
    BookDto dto = converter.toDto(book);

    given(bookController.createBook(dto)).willReturn(dto);

    mockMvc.perform(post("/api/books/create")
                    .contentType(MediaType.APPLICATION_JSON).content(asJsonString(book)))
            .andExpect(status().isCreated());
}

@Test
public void getAllBooks_success() throws Exception {

    Book book1 = Book.builder().name("New book").author("Ivan").build();
    Book book2 = Book.builder().name("This book").author("Whatever").build();

    List<Book> bookList = new ArrayList<>(Arrays.asList(book1, book2));

    Mockito.when(bookController.getAllBooks()).thenReturn(bookList);

    mockMvc.perform(MockMvcRequestBuilders.get("/api/books/all")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(2)))
            .andExpect(jsonPath("$[0].name", is("New book")));
}

@Test
public void findByTitle_success() throws Exception {
    Book book = Book.builder().name("New book").author("Ivan")
            .pagesNumber(340).publisher("New Publisher").build();

    BookDto dto = converter.toDto(book);

    Mockito.when(bookController.findByTitle(book.getName())).thenReturn(dto);

    LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
    requestParams.add("name", "New book");

    mockMvc.perform(MockMvcRequestBuilders.get("/api/books/byTitle").params(requestParams)
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}
private String asJsonString(final Object obj){
    try{
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e){
        throw new RuntimeException(e);
    }
}
}

PS是否有有关在测试中实施身份验证的文章或文档?将不胜感激。

I added a basic auth to my Spring app in application.properties like this:

  #Security
  security:
    user:
      name: admin
      password: admin

I also added spring-boot-starter-security to make it work. Now I'm curious how I need to refactor controller tests as after I implemented basic auth all of those tests returned 401 status. I am using junit5 and mockito. This is the ControllerTests class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = BooksApplication.class)
@AutoConfigureMockMvc
class BookControllerTests {
@Autowired
MockMvc mockMvc;

@Autowired
ObjectMapper mapper;
@MockBean
BookController bookController;

@Autowired
private BookConverter converter;

@Test
public void createBook_success() throws Exception {
    Book book = Book.builder().name("Great book").author("Ivan")
            .pagesNumber(340).publisher("New Publisher").build();
    BookDto dto = converter.toDto(book);

    given(bookController.createBook(dto)).willReturn(dto);

    mockMvc.perform(post("/api/books/create")
                    .contentType(MediaType.APPLICATION_JSON).content(asJsonString(book)))
            .andExpect(status().isCreated());
}

@Test
public void getAllBooks_success() throws Exception {

    Book book1 = Book.builder().name("New book").author("Ivan").build();
    Book book2 = Book.builder().name("This book").author("Whatever").build();

    List<Book> bookList = new ArrayList<>(Arrays.asList(book1, book2));

    Mockito.when(bookController.getAllBooks()).thenReturn(bookList);

    mockMvc.perform(MockMvcRequestBuilders.get("/api/books/all")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("
quot;, hasSize(2)))
            .andExpect(jsonPath("$[0].name", is("New book")));
}

@Test
public void findByTitle_success() throws Exception {
    Book book = Book.builder().name("New book").author("Ivan")
            .pagesNumber(340).publisher("New Publisher").build();

    BookDto dto = converter.toDto(book);

    Mockito.when(bookController.findByTitle(book.getName())).thenReturn(dto);

    LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
    requestParams.add("name", "New book");

    mockMvc.perform(MockMvcRequestBuilders.get("/api/books/byTitle").params(requestParams)
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}
private String asJsonString(final Object obj){
    try{
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e){
        throw new RuntimeException(e);
    }
}
}

P.S. Is there any article or documentation about implementing authentication in tests? Will be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青衫负雪 2025-02-18 00:42:36

检查弹簧安全文档 - https://docs.spring.io/spring-security/referenty/5.6.5/servlet/test/method.html#test-method-method-withmockuser

您可以使用@withmockuser 注释,它提供用户名 - 用户和密码 - 密码以及角色-COARE_USER的默认凭据

Check the Spring Security Documentation - https://docs.spring.io/spring-security/reference/5.6.5/servlet/test/method.html#test-method-withmockuser

You can use the @WithMockUser annotation, which provides default credentials with username - user and password - password, and with the role - ROLE_USER

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文