基于 URL 编码方法的 JUnit 测试用例

问题描述 投票:0回答:1

我做了一些更改以激活斜线编码的 URL,有关详细信息 它工作正常,我想在运行 IT 测试时激活这些更改。
我如何激活 UserserviceApplication 上的这些更改。

@SpringBootApplication
    @EnableDiscoveryClient
    @EnableCaching
    public class UserserviceApplication implements WebMvcConfigurer {
    
    
        public static void main(String[] args) {
            System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
            SpringApplication.run(UserserviceApplication.class, args);
        }
    
        public void configurePathMatch(PathMatchConfigurer configurer) {
            UrlPathHelper urlPathHelper = new UrlPathHelper();
            urlPathHelper.setUrlDecode(false);
            configurer.setUrlPathHelper(urlPathHelper);
        }
    
    }
    
    
    @ActiveProfiles("it")
    @RunWith(SpringRunner.class)
    @TestPropertySource(locations = "classpath:application-it.properties")
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    
    public class TeamControllerIT {
    
        @LocalServerPort private int port;
    
        @Autowired private Environment environment;
java spring-boot junit spring-test
1个回答
0
投票

这是我准备的工作代码。重点之一是 setUrlEncodingEnabled() 和 urlEncodingEnabled()。 您也可以查看以下链接 CustomAppContext RestAssure URL 编码

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

public class CustomApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext)
    {
        System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
    }
}



import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

@ActiveProfiles("it")
@RunWith(SpringRunner.class)
@TestPropertySource(locations = "classpath:application-it.properties")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = CustomApplicationContextInitializer.class)

public class TeamControllerIT {

    @LocalServerPort
    private int port;

    @Autowired
    private Environment environment;

    private RequestSpecification correctCredentialsPortSpecUrlEncodedForService;

    @MockBean
    private TeamService teamService;

    @Before
    public void setUp() throws Exception {
        JSONArray rolesArray = new JSONArray();
        rolesArray.put("user");
      

        String token = JWTUtil.createSelfSignedTestToken(environment.getProperty("publickey"),
                environment.getProperty("privatekey"), Date.valueOf(LocalDate.parse("2999-01-01")), "integrationTest",
                environment.getProperty("testclient"), rolesArray);

        correctCredentialsPortSpecUrlEncodedForService = new RequestSpecBuilder()
                .addHeader("Authorization", "Bearer " + token)
                .setPort(port)
                .setUrlEncodingEnabled(false)
                .build();
    }


    @Test
    public void shouldGetUsersInTeam() throws UnsupportedEncodingException {

        String teamID = "slash/slash";

        when(teamService.getTeamUsers(teamID)).thenReturn(List.of(
                User.builder().userId("user1").firstName("user").lastName("1").email("[email protected]").build(),
                User.builder().userId("user2").firstName("user").lastName("2").email("[email protected]").build()
        ));


        List<KeycloakUserDTO> list2 =
                given()
                        .spec(correctCredentialsPortSpecUrlEncodedForService)
                        .log().ifValidationFails()
                        .contentType("application/json")
                        .urlEncodingEnabled(false)
                        .pathParam("teamIDEncoded", urlEncodeString(teamID))
                        .when()
                        .get("/userservice/teams/{teamIDEncoded}/users")
                        .then()
                        .log().ifValidationFails()
                        .statusCode(200)
                        .and().extract().jsonPath().getList("", KeycloakUserDTO.class);

        assertThat(list2.size()==2);
    }

    private static String urlEncodeString(String value) throws UnsupportedEncodingException {
        return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
    }

    private String activeProfile() {
        return environment.getActiveProfiles()[0];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.