首页  >  文章  >  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 可以从空手道测试中受益匪浅,但是如何在空手道测试中直接利用 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