在 junit 测试用例中需要更改使用 preAuthorize 注释到通过 Jhipster 生成的 api

changes required in junit test cases on using preAuthorize annotation to api generated through Jhipster

我创建了一个 jhipster 项目并添加了一个实体(实体名称 压力)。 rest controller、service、repository和junit测试用例的所有代码都是通过jhipster自动生成的。

我通过添加注释

保护了实体的创建、更新和删除api
@PreAuthorize("hasAuthority('ROLE_ADMIN')")

当我 运行

时,这些受保护 api 的默认 junit 测试用例失败
./mvnw verify

格式错误

[ERROR] Failures:
[ERROR]   PressureResourceIT.createPressure:210 Status expected:<201> but was:<403>
[ERROR]   PressureResourceIT.createPressureWithExistingId:251 Status expected:<400> but was:<403>
[ERROR]   PressureResourceIT.deletePressure:2629 Status expected:<204> but was:<403>
[ERROR]   PressureResourceIT.updateNonExistingPressure:2611 Status expected:<400> but was:<403>
[ERROR]   PressureResourceIT.updatePressure:2573 Status expected:<200> but was:<403>

我知道自动生成的测试代码无法处理 api 之后使用 preAuthorize 注释保护的代码,这就是状态代码 403(禁止)的原因。

我需要帮助,了解需要对 junit 测试用例代码进行哪些修改。例如,下面的测试用例需要进行哪些更改?

    @Test
    @Transactional
    public void createPressureWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = pressureRepository.findAll().size();

        // Create the Pressure with an existing ID
        pressure.setId(1L);

        // An entity with an existing ID cannot be created, so this API call must fail
        restPressureMockMvc.perform(post("/api/pressures").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(pressure)))
            .andExpect(status().isBadRequest());

        // Validate the Pressure in the database
        List<Pressure> pressureList = pressureRepository.findAll();
        assertThat(pressureList).hasSize(databaseSizeBeforeCreate);
    }

这里没有特定于 JHipster 的东西,Spring 安全性有你需要的一切,特别是你可以用 @WithMockUser(roles="ADMIN")

注释你的测试

查看官方文档: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#running-as-a-user-in-spring-mvc-test-with-annotations

您得到的错误实际上非常好,并且正是使用这些测试的重点。

您将收到 403 响应,这意味着:未经授权。这样做的原因是,当您未以管理员身份登录时,您将无法访问这些端点。

您应该使失败的测试用例适应新情况,在这种情况下您需要管理员登录这些端点

添加:@WithMockUser(roles="ADMIN") 到您的测试用例以模拟用户以管理员身份登录

此外,您可以添加在您 以管理员身份登录时成功的测试用例,但您仍然尝试访问这些端点(您的测试用例现在所处的状态).这些组合应该会产生 403 响应。添加断言:

.andExpect(status().isUnauthorized());