java - @WithMockUser 在集成测试中不起作用 - Spring boot

标签 java spring spring-security spring-boot

尽管我的测试方法使用@WithMockUser 进行了注释,但我仍然遇到访问被拒绝的情况。为什么这在集成测试中不起作用?使用@WebAppConfiguration 和 MockMvc 测试一切正常。

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FileUploadIntegrationTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @MockBean
    private FileStorageService storageService;

    @Test
    public void classPathResourceTest() throws Exception {
        ClassPathResource resource = new ClassPathResource("/test/testFile.txt", getClass());
        assertThat(resource.exists(), is(true));
    }

    @Test
    @WithMockUser(username="tester",roles={"USER"})
    public void shouldUploadFile() throws Exception {
        ClassPathResource resource = new ClassPathResource("/test/testFile.txt", getClass());

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("file", resource);
        ResponseEntity<String> response = this.restTemplate.postForEntity("/files", map, String.class);

//        assertThat(response.getStatusCode(), is(HttpStatus.OK));
        then(storageService).should().addFile((any(String.class)), any(MultipartFile.class));
    }
}

Controller 类:

@RestController
@RequestMapping("/files")
@PreAuthorize(value = "hasRole('ROLE_USER')")
public class FileUploadController {

    private FileStorageService fileStorageService;
    private AuthenticationFacade authenticationFacade;

    @Autowired
    public FileUploadController(FileStorageService fileUploadService, AuthenticationFacade authenticationFacade) {
        this.fileStorageService = fileUploadService;
        this.authenticationFacade = authenticationFacade;
    }

    @ResponseBody
    @PostMapping
    public ResponseEntity<UUID> uploadFile(@RequestParam("file") MultipartFile file) {
        UUID uuid = this.fileStorageService.addFile(authenticationFacade.getAuthentication().getName(), file);
        if (uuid != null) return ResponseEntity.ok(uuid);
        else return (ResponseEntity<UUID>) ResponseEntity.badRequest();
    }

}

最佳答案

无法使用@WithMockUser 解决此问题。

您可以尝试使用此处描述的配置文件方法:https://stackoverflow.com/a/35192495/3010484 .

关于java - @WithMockUser 在集成测试中不起作用 - Spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40906909/

相关文章:

java - 使用 Spring 的 Google App Engine GAE MemcacheService 单例注入(inject)

java - 没有使用 Spring Security 进行身份验证和授权

java - 我如何创建受方法安全保护的 DAO 的安全版本和不安全版本

java - 从JAVA中的各种JCheckboxes在mysql中输入各种值

java - Java中前缀和后缀++运算符的区别

eclipse - 必须为 ... ApplicationRequestFactory RequestFactory 类型运行 RequestFactory ValidationTool

spring - Spring Websocket 中的请求或 session 范围

java - 通过反射从 import static 获取类中的静态变量

Java - 获取网页内容跳过中间页面以响应达到所需的响应

java - Spring 安全 : how to pass additional user info to JSP?