如何将身份验证添加到控制器测试弹簧中?
我在应用程序中的春季应用中添加了一个基本验证。
#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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查弹簧安全文档 - 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