You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试带@PreAuthorize hasAuthority()注解的接口返回404如何解决

单元测试404错误原因与解决方案

错误原因

  • 请求路径写法错误:MockMvc的请求方法不需要传入完整的域名+端口,你写的http://localhost:9092/profile/{fileKey}会被识别为路径的一部分,实际发起的请求路径和你控制器定义的/profile/{fileKey}不匹配,触发404。
  • 测试组件不匹配:控制器返回Mono类型,属于Spring WebFlux响应式接口,你当前使用的MockMvc是Spring MVC的测试组件,无法识别WebFlux的路由映射,也会导致404。
  • 额外潜在问题:你使用@WithMockUser模拟的是普通用户名密码认证的权限,无法满足接口参数注入Jwt类型认证主体的要求,路径问题解决后会出现类型转换错误;另外接口成功响应码定义为204,你测试断言写的200也会导致最终断言失败。

解决方法

1. 调整测试注解与依赖组件(WebFlux项目适用)

如果是WebFlux项目,将测试替换为WebFlux专属测试组件,修改测试类如下:

import com.backend.StorageController;
import com.backend.config.Config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Config.class)
@SpringBootTest
@AutoConfigureWebTestClient
public class Tests {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void testDeleteCardProfile() throws Exception {
        webTestClient.mutateWith(SecurityMockServerConfigurers.mockJwt()
                        .authorities(() -> "admin"))
                .delete()
                .uri("/profile/{fileKey}", "VOlUc3F5A_test.txt")
                .exchange()
                .expectStatus().isNoContent(); // 接口定义成功返回204,对应isNoContent
    }
}

2. 若确认项目是Spring MVC项目(非WebFlux)

直接修改请求路径即可,删除完整域名端口:

// 仅修改delete方法的入参路径即可
MvcResult result = mockMvc.perform(MockMvcRequestBuilders
        .delete("/profile/{fileKey}", "VOlUc3F5A_test.txt")
        .with(SecurityMockMvcRequestPostProcessors.csrf())).andReturn();
// 同时调整断言为204和适配Jwt模拟逻辑
Assert.assertEquals(204, result.getResponse().getStatus());

内容的提问来源于stack exchange,提问作者karthik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:48:03