
几年来,我一直使用 cucumber 进行更高级别的测试,最近才开始使用空手道。虽然 cucumber 是一个很棒的工具,但我认为空手道真正的亮点在于减少了步骤定义带来的样板文件,并使快速编写有意义的测试变得容易,尤其是在 api 测试方面。
对于简单的应用程序,用纯 javascript 编写功能文件就足够了。随着应用程序和测试的增长,重用一些 java 代码可能会变得有价值。 spring boot api 可以从空手道测试中受益匪浅,但是如何在空手道测试中直接利用 spring boot 的强大功能呢?
一些示例用例
如何将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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号