2016-12-01 84 views
7

雖然我的測試方法使用@WithMockUser進行了註釋,但我仍然遇到Access Denied。爲什麼這不適用於集成測試?通過使用@WebAppConfiguration和MockMvc進行測試,一切都很好。@WithMockUser無法在集成測試中工作 - 春季啓動

測試類:

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

} 
+0

你解決了嗎?我有問題要讓這個工作以及 – BigDong

+0

不幸的是;/ – Milso

+0

你使用彈簧安全oauth2? – BigDong

回答