【问题标题】:@WithMockUser doesn't work in Integration Test - Spring boot@WithMockUser 在集成测试中不起作用 - Spring boot
【发布时间】:2017-04-15 20:54:04
【问题描述】:

尽管我的测试方法使用@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));
    }
}

控制器类:

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

}

【问题讨论】:

  • 你解决了吗?我也有问题要让它工作
  • 很遗憾没有;/
  • 你使用spring security oauth2吗?
  • 是的,我用过——这里是这个模块的仓库:github.com/MarcinMilewski/sqap-api

标签: java spring spring-security spring-boot


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 2019-08-10
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 2017-01-05
    • 2018-01-01
    • 2021-04-05
    • 2020-02-25
    相关资源
    最近更新 更多