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

huangapple go评论77阅读模式
英文:

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

问题

我创建了一个JHipster项目,并添加了一个实体(实体名称Pressure)。所有的REST控制器、服务、存储库和JUnit测试用例的代码都是通过JHipster自动生成的。

我通过添加注解来保护实体的创建、更新和删除API,注解如下:

@PreAuthorize("hasAuthority('ROLE_ADMIN')")

当我运行

./mvnw verify

时,这些受保护的API的默认JUnit测试用例失败。错误的格式如下:

[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>

我理解自动生成的测试代码无法处理后来使用PreAuthorize注解保护的API,这就是为什么状态码为403(禁止)的原因。

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

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

        // 使用现有ID创建Pressure
        pressure.setId(1L);

        // 无法创建具有现有ID的实体,因此此API调用必须失败
        restPressureMockMvc.perform(post("/api/pressures").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(pressure)))
            .andExpect(status().isBadRequest());

        // 验证数据库中的Pressure
        List<Pressure> pressureList = pressureRepository.findAll();
        assertThat(pressureList).hasSize(databaseSizeBeforeCreate);
    }
英文:

I created a jhipster project and added an entity(entity name Pressure). All the codes of rest controller, service, repository and junit test cases are auto generated through jhipster.

I protected the create, update and delete api of the entity by adding annotation

@PreAuthorize(&quot;hasAuthority(&#39;ROLE_ADMIN&#39;)&quot;)

The default junit test cases fails for these protected api when i run

./mvnw verify

The error is in the format

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

I understand that auto generated test codes are not able to handle api that are later protected using preAuthorize annotation, that's why the status code 403 (forbiden).

I need help, to know what modifications are required to the junit test case code. Say for example, what changes will be required to below test case?

    @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(&quot;/api/pressures&quot;).with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(pressure)))
            .andExpect(status().isBadRequest());

        // Validate the Pressure in the database
        List&lt;Pressure&gt; pressureList = pressureRepository.findAll();
        assertThat(pressureList).hasSize(databaseSizeBeforeCreate);
    }

答案1

得分: 2

没有特定于JHipster的内容,在这里,Spring Security已经提供了你所需要的一切,特别是你可以使用@WithMockUser(roles=&quot;ADMIN&quot;)为你的测试添加注释。

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

英文:

Nothing specific to JHipster here, Spring security has all you need, in particular you could annotate your test with @WithMockUser(roles=&quot;ADMIN&quot;)

See official docs:
https://docs.spring.io/spring-security/site/docs/current/reference/html5/#running-as-a-user-in-spring-mvc-test-with-annotations

答案2

得分: 0

收到,以下是您要翻译的内容:

错误信息实际上是非常有用的,也正是使用这些测试的目的所在。

您收到了一个403响应,意味着:未经授权。造成这种情况的原因是,当您没有以管理员身份登录时,您无权访问那些端点。

您应该根据新的情况调整未通过的测试用例,您现在需要一个管理员登录才能访问这些端点。

将以下内容添加到您的测试用例中:@WithMockUser(roles=&quot;ADMIN&quot;),以模拟以管理员身份登录的用户。

此外,您还可以添加在您没有以管理员身份登录的情况下仍然尝试访问这些端点的测试用例(即您现在的测试用例状态)。这些组合应该会导致403响应。添加断言:

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

英文:

The errors you get are actually very good, and exactly the point of using these tests.

You are getting back a 403 response which means: Unauthorized. The reason for this is that when you are not logged in as an Admin, you are not allowed to access those endpoints.

You should adapt your failing testcase to the new situation, where you need an admin to be logged in for those endpoints

add: @WithMockUser(roles=&quot;ADMIN&quot;) to your testcase to mock the user being logged in as an admin

And also, you could add testcases that succeed when you are not logged in as an admin, but you still try to access these endpoints (the state your testcases are in now). These combinations should result in a 403 response. Add the assertion:

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

huangapple
  • 本文由 发表于 2020年8月18日 17:39:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63465919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定