>  기사  >  Java  >  Spring Boot DI로 가라테 테스트 수준을 높이세요

Spring Boot DI로 가라테 테스트 수준을 높이세요

WBOY
WBOY원래의
2024-07-22 16:44:47560검색

Level up your Karate Testing with Spring Boot DI

몇 년 동안 저는 더 높은 수준의 테스트를 위해 Cucumber를 사용해 왔으며 최근에는 Karate를 사용하기 시작했습니다. Cucumber는 훌륭한 도구이지만 Karate는 단계 정의와 함께 제공되는 상용구를 줄이고 특히 API 테스트와 관련하여 의미 있는 테스트를 빠르고 쉽게 작성할 수 있도록 한다는 점에서 정말 빛을 발한다고 생각합니다.

간단한 애플리케이션의 경우 일반 JavaScript로 기능 파일을 작성하는 것으로 충분합니다. 애플리케이션과 테스트가 성장함에 따라 일부 Java 코드를 재사용하는 것이 중요해질 수 있습니다. Spring Boot API는 Karate 테스트에서 많은 이점을 얻을 수 있지만 Karate 테스트에서 직접 Spring Boot의 기능을 활용하는 것은 어떻습니까?

몇 가지 사용 사례

  • Karate는 karate-config.js 파일을 통한 구성을 지원하지만 일부는 대신 Spring YAML/properties를 통한 구성을 선호할 수도 있습니다. 이는 코드 재구축 외에도 항목을 재구성하는 데 도움이 될 수 있습니다.
  • 애플리케이션과 테스트 간에 특정 Spring Boot 구성 속성을 동기화합니다.
  • API 호출 간 데이터베이스 상태를 확인합니다. JPA 저장소/엔티티 빈은 Karate 테스트에 사용될 수 있습니다.
  • 일부 Spring 빈은 테스트에 활용하는 데 유용할 수도 있습니다.

Spring을 Karate에 통합하는 방법

전체 샘플 프로젝트: https://github.com/trey-pero/karate-spring

Karate는 간단한 JUnit 테스트를 통해 실행할 수 있습니다. Spring in 연결을 시작하려면 JUnit 테스트를 @SpringBootTest로 설정하세요.

@RequiredArgsConstructor
@SpringBootTest(classes = Main.class)
public class KarateTest {
    private final ApplicationContext applicationContext;

    @Test
    void test() {
        ApplicationContextHolder.setApplicationContext(this.applicationContext);

        // Since this one JUnit test runs all Karate tests,
        // fail the test if any underlying Karate tests fail
        assertEquals(0, Runner.path("classpath:org/tpero")
                .parallel(Optional.ofNullable(System.getProperty("karate.threads"))
                        .map(Integer::parseInt)
                        .orElse(5)
                ).getFailCount());
    }
}

Spring 컨텍스트(모든 Bean 및 구성에 대한 액세스 제공)에 액세스하려면 Karate가 정적으로 액세스할 수 있는 위치에 저장해야 합니다.

/**
 * Provides Karate static access to the Spring application context.
 */
@UtilityClass
public class ApplicationContextHolder {
    @Setter
    @Getter
    private ApplicationContext applicationContext;
}

Karate 구성에서 정적 홀더에 액세스하여 다음 샘플을 사용하여 애플리케이션 컨텍스트를 Karate의 전역 구성 맵에 연결할 수 있습니다.

/**
 * Define common feature file configuration here.
 * @returns Common configuration as a JSON object.
 */
function getConfig() {
    // Global values
    const appContext = Java.type("org.tpero.ApplicationContextHolder")
        .getApplicationContext()
    const environment = appContext.getEnvironment()

    return {
        appContext: appContext,
        environment: environment,

        baseUrl: `http://localhost:${environment.getProperty('app.server.port', '8080')}`
    }
}

위의 설정 코드를 사용하면 JWT 토큰을 반환하는 간단한 로그인 API를 테스트하는 이 샘플에서 볼 수 있듯이 Karate 기능 파일에서 Bean과 구성에 액세스할 수 있습니다.

Feature: Login
  Background:
    * url baseUrl
    * path '/login'
    # Load the JWT service bean from Spring DI
    * def jwtService = appContext.getBean('jwtService')

  Scenario: Login with valid credentials
    Given request { username: 'user', password: 'password' }
    When method post
    Then status 200
    * print response

    # Use the JWT service bean to decode the JWT from the response
    * def decodedJwt = jwtService.decode(response)
    * print decodedJwt
    * def decodedBody = decodedJwt.getBody()
    * print decodedBody

    And match decodedBody['sub'] == 'user'
    * def issuedAt = Number(decodedBody['iat'])
    # Ensure the issuedAt is in the past
    And assert issuedAt < Java.type('java.lang.System').currentTimeMillis()
    * def configuredExpirationInMinutes = Number(environment.getProperty('jwt.expiration.ms')) / 1000
    # Ensure the expiration is the configurable amount of minutes beyond the issuedAt
    And match Number(decodedBody['exp']) == issuedAt + configuredExpirationInMinutes

이 샘플은 Spring Boot의 강력한 기능을 Karate에 통합하여 더 많은 기능을 갖춘 테스트 모음을 구축하는 것이 얼마나 쉬운지 보여줍니다.

위 내용은 Spring Boot DI로 가라테 테스트 수준을 높이세요의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.