首頁  >  文章  >  Java  >  使用 Spring Boot DI 提升您的空手道測驗水平

使用 Spring Boot DI 提升您的空手道測驗水平

WBOY
WBOY原創
2024-07-22 16:44:47563瀏覽

Level up your Karate Testing with Spring Boot DI

幾年來我一直使用 Cucumber 進行更高級別的測試,最近才開始使用 Karate。雖然 Cucumber 是一個很棒的工具,但我認為 Karate 真正的亮點在於減少了步驟定義帶來的樣板文件,並且可以輕鬆快速地編寫有意義的測試,尤其是在 API 測試方面。

對於簡單的應用程序,用純 JavaScript 編寫功能文件就足夠了。隨著應用程式和測試的成長,重複使用一些 Java 程式碼可能會變得有價值。 Spring Boot API 可以從空手道測驗中受益匪淺,但如何在空手道測驗中直接利用 Spring Boot 的強大功能呢?

一些範例用例

  • 雖然 Karate 支援透過 karate-config.js 檔案進行配置,但有些人可能喜歡透過 Spring YAML/properties 進行配置。這對於重建程式碼以外的重新配置也很有幫助。
  • 在應用程式和測試之間同步某些 Spring Boot 配置屬性。
  • 驗證 API 呼叫之間的資料庫狀態。 JPA 儲存庫/實體 bean 可以在空手道測驗中使用。
  • 一些 Spring beans 在測試中可能非常有用。

如何將 Spring 融入空手道

完整範例專案:https://github.com/trey-pero/karate-spring

空手道可以透過簡單的 JUnit 測試來執行。若要開始連接 Spring,請將 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')}`
    }
}

使用上述設定程式碼,可以從 Karate 功能檔案存取 beans 和配置,如本範例所示,此範例測試傳回 JWT 令牌的簡單登入 API。

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