Spring Boot测试中发生HTTP 401未经授权的错误

时间:2020-07-04 19:03:23

标签: java spring spring-boot spring-security spring-test

实体类

@Getter
@NoArgsConstructor
@Entity
public class Posts {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(length = 500, nullable = false)
    private String title;
    
    @Column(columnDefinition = "TEXT", nullable = false)
    private String content;
    
    private String author;
    
    @Builder
    public Posts(String title, String content, String author) {
        this.title = title;
        this.content = content;
        this.author = author;
    }
}

测试代码

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PostsAPIControllerTest {
    @LocalServerPort
    private int port;
    
    @Autowired
    private TestRestTemplate restTemplate;
    
    @Autowired
    private PostsRepository postsRepository; // PostsRepository extends JpaRepository<Posts, Long>
    
    @After
    public void tearDown() throws Exception {
        postsRepository.deleteAll();
    }
    
    @Test
    public void posts_save() throws Exception {
        String title = "title";
        String content = "content";
        
        PostsSaveRequestDTO requestDTO = PostsSaveRequestDTO.builder()
                                                            .title(title)
                                                            .content(content)
                                                            .author("author")
                                                            .build();
        
        String url = "http://localhost:" + port + "/api/v1/posts";
        ResponseEntity<Long> responseEntity = restTemplate.postForEntity(url, requestDTO, Long.class);
        
        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(responseEntity.getBody()).isGreaterThan(0L);
        
        List<Posts> all = postsRepository.findAll();
        
        assertThat(all.get(0).getTitle()).isEqualTo(title);
        assertThat(all.get(0).getContent()).isEqualTo(content);
    }
}

控制器

@RequiredArgsConstructor
@RestController
public class PostsAPIController {
    private final PostsService postsService;
    
    @PostMapping("/api/v1/posts")
    public Long save(@RequestBody PostsSaveRequestDTO requestDTO) {
        return postsService.save(requestDTO);
    }
    
    @PutMapping("/api/v1/posts/{id}")
    public Long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDTO requestDTO) {
        return postsService.update(id, requestDTO);
    }
    
    @GetMapping("/api/v1/posts/{id}")
    public PostsResponseDTO findById(@PathVariable Long id) {
        return postsService.findById(id);
    }
}

我制作了一个示例Spring Boot测试代码来更新数据库,但是如果执行代码,测试失败并显示以下错误消息。我已经为application.properties文件定义了spring.security.user.namespring.security.user.password

出什么问题了?从build.gradle中删除testImplementation 'org.springframework.security:spring-security-test'后,我尝试重新加载,但是没有任何改变。

Expecting:
 <401 UNAUTHORIZED>
to be equal to:
 <200 OK>
but was not.

1 个答案:

答案 0 :(得分:0)

有多种使用@WithMockUser, @WithAnonymousUser, @WithUserDetails, @WithSecurityContext模拟安全性的方法。您可以通过@Test方法使用这些注释 您可以根据项目要求更改角色。您可能想探索更多详细信息,here

@Test
@WithMockUser(username="admin",roles="ADMIN")
public void posts_save() throws Exception {
    String title = "title";
    String content = "content";
    
    PostsSaveRequestDTO requestDTO = PostsSaveRequestDTO.builder()
                                                        .title(title)
                                                        .content(content)
                                                        .author("author")
                                                        .build();
    
    String url = "http://localhost:" + port + "/api/v1/posts";
    ResponseEntity<Long> responseEntity = restTemplate.postForEntity(url, requestDTO, Long.class);
    
    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(responseEntity.getBody()).isGreaterThan(0L);
    
    List<Posts> all = postsRepository.findAll();
    
    assertThat(all.get(0).getTitle()).isEqualTo(title);
    assertThat(all.get(0).getContent()).isEqualTo(content);