【发布时间】:2021-12-19 23:21:24
【问题描述】:
刚开始编写 Cucumber 测试...
使用 Java 1.8 和 SpringWebFlux,我在我的服务类中创建了以下检查(从 Spring 框架 @RestController 的 HTTP POST 请求中获取值)。
我正在检查accountId(它是一个字符串)是否不为空、空字符串并且也不能包含任何空格。
@Service
public class MyServiceImpl implements MyService
@Override
public Mono<CustomResponse> postAccount(MyRequest myRequest) {
if (myRequest.getAccountId() == null
|| "".equals(myRequest.getAccountId())
|| myRequest.getAccountId().contains(" ")) {
log.error("accountId was invalid {}", myRequest.getAccountId());
return Mono.empty();
}
// Omitted if nothing failed for code brevity purposes.
}
}
在我的服务类的集成测试中:
@Test
void invalidAccountIds() {
// Checks for empty string
CustomResponse response1 = myService.postAccount(new MyRequest().accountId(""), context).block();
// Checks for null string
CustomResponse response2 = myService.postAccount(new MyRequest().accountId(null), context).block();
// Checks for whitespace
CustomResponse response3 = myService.postAccount(new MyRequest().accountId(" "), context).block();
assertNull(response1, "accountId cannot be null");
assertNull(response2, "accountId cannot be empty string");
assertNull(response3, "accountId cannot whitespaces");
}
这在mvn clean install时完全有效
但是,我的 Cucumber 测试失败了:
@apiTest
Feature: MyService POST API test and verify response
Scenario Outline: I verify API fields for MyService
Given I have an jwt OAuth token
When I make an async POST request myRequest to default:/api/v1/accounts:
"""
Authorization: Bearer $OAUTHTOKEN
user-agent: MyService/cucumberTest/<testCase>
{
"accountId" : <accountId>
}
"""
Then The async request MyRequest has http code <status>
Examples:
| testCase | accountId | status |
| inputField1 | " " | 400 |
| inputField2 | 1 | 400 |
为什么 inputField1 和 inputField2 返回 HTTP 200 而不是 HTTP 400?
我需要 accountId 始终是字符串,而不是数字...
我需要在 Cucumber 步骤中添加什么才能使这些步骤成为 HTTP 400?
【问题讨论】:
-
您不只是使用 Bean Validation 的任何特殊原因?
@NotBlank会正常工作。 (另外,我一般不使用 Webflux,但我希望Mono.empty()返回一个空但成功的响应。) -
@chrylis-cautiouslyoptimistic- 感谢您的快速回复!我会在哪里附加
@NotBlank?另外,我故意省略了验证良好的部分。我使用 Mockito(见上文)的集成测试有效,但我的 Cucumber 测试无效。这更具体到 Cucumber - 我在 Cucumber 步骤中放了什么? -
@Sebastiann - 我没有在这篇文章中包含我的
@RestController类中的 throws HTTP 400,以使这篇文章尽可能简洁。我只需要我的 Cucumber 测试来查看 HTTP 400。我会在 Cucumber 步骤中添加什么? -
你也可以回复我的回答,会更容易看到。但我认为您应该展示您的代码,以便它实际上是您正在测试的内容。现在在代码中没有抛出 400 的地方,所以我们无法弄清楚为什么它在实际代码中没有返回 400。
-
查找 Bean 验证。它来自
spring-boot-starter-validation。
标签: java cucumber spring-webflux