当前位置: 首页 > 知识库问答 >
问题:

Spring安全Spring启动测试控制器

赵炯
2023-03-14

我正在测试家庭控制器

@RequestMapping("/")
@ResponseBody
String home() {
    return "Hello World!";
}

我使用spring security作为用户名“user”,默认情况下作为密码进行测试,但@PreAuthorize不起作用

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@PreAuthorize("hasRole('ADMIN')")
public class HomeControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    @WithMockUser(username = "user", password = "test", roles = "ADMIN")
    public void home() throws Exception {
        String body = this.restTemplate.getForObject("/", String.class);
        assertThat(body).isEqualTo("Hello World!");
    }

}

的结果

预期结果:

实际结果:

我错过了什么吗?

共有1个答案

经俊茂
2023-03-14

尝试将以下内容添加到您的测试类中:

@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS, listeners = {
        WithSecurityContextTestExecutionListener.class
})

如果您没有以下依赖项:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

Spring Security性需要一个默认情况下不存在于测试中的额外侦听器,因此您需要通过在合并模式下指定@TestExecutionListeners注释来告诉Spring添加它,以便它将当前列出的侦听器与您要添加的侦听器合并-在这种情况下WitSecurityContextTestExecutionListener

 类似资料:
  • 我正在尝试测试以下控制器: 下面是测试类: 当我运行测试失败,并给我以下消息: 当我测试的url正常工作。

  • 我使用angular2作为前端和Spring启动Rest控制器。在添加Spring安全性之前,我的应用程序工作正常。添加安全性后,带参数的函数不会在Spring启动Rest控制器中调用。下面是代码 在我加入spring security之前http://localhost:4200,所有这些都被称为“/jobcleanup”、“/jobcleanupclosedtickets”、“/JobClea

  • 我的应用程序有Spring boot 1.3.2,我正在尝试将Spring MVC与Spring Security结合使用。 我有管理小组http://localhost:8080/admin和我的普通用户页面内容http://localhost:8080/ 如果你试图打开一个管理面板(http://localhost:8080/admin)你必须登录,如果你是常见的只需输入http://loca

  • 2020-05-09 17:28:38.521信息21308---[restartedMain]O.A.C.C.C.[Tomcat].[localhost].[/]:初始化Spring embedded WebApplicationContext 2020-05-09 17:28:38.527信息21308--[restartedMain]O.s.Web.context.ContextLoader

  • 尝试用junit5和mockito测试我的web层(spring boot、spring mvc)。http方法的所有其他测试(get、put等)工作正常,但更新。遵循代码。 控制器: 服务: 最后,测试: 结果: CustomerService中的update(...)方法返回为null。无法理解方式。请建议。

  • 我试图使用mockmvcbuilders.standalonesetup方法为一个spring mvc rest控制器创建一个非常基本的单元测试。我一直收到一个404错误。下面列出了测试应用程序上下文、测试类、控制器和整个堆栈跟踪。欢迎任何指导。 java.lang.AssertionError:状态应为:<200>但实际为:<404>在org.springframework.test.util.