gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:35:35 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com