ホームページ  >  記事  >  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 を使用してきましたが、空手を使い始めたのはつい最近のことです。 Cucumber は優れたツールですが、Karate は、特に API テストに関して、ステップ定義に伴う定型文を削減し、有意義なテストを迅速に簡単に作成できる点で本当に優れていると思います。

単純なアプリケーションの場合は、プレーンな JavaScript で機能ファイルを作成するだけで十分です。ただし、アプリケーションとテストが成長するにつれて、一部の Java コードを再利用することが重要になる場合があります。 Spring Boot API は空手テストから多くのメリットを得ることができますが、空手テストで Spring Boot の機能を直接活用するのはどうでしょうか?

いくつかの使用例

  • Karate は karate-config.js ファイルによる設定をサポートしていますが、代わりに Spring YAML/プロパティによる設定を好む人もいるかもしれません。これは、コードの再構築以外の部分を再構成する場合にも役立ちます。
  • アプリケーションとテスト間で特定の Spring Boot 構成プロパティを同期するため。
  • API 呼び出し間のデータベースの状態を確認します。 JPA リポジトリ/エンティティ Bean は、Karate テストで使用できる可能性があります。
  • 一部の Spring Bean は、テストで利用するのに単に役立つ場合があります。

春を空手に組み込む方法

完全なサンプルプロジェクト: 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')}`
    }
}

上記のセットアップ コードを使用すると、Karate 機能ファイルから Bean と設定にアクセスできます。これは、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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。