Java 中的 Cucumber 测试中如何防止数字和空格传递给字符串?

How to prevent number and whitespace to pass for String in Cucumber test in Java?

我是编写 Cucumber 测试的新手...

使用 Java 1.8 和 SpringWebFlux,我在我的服务 class 中创建了以下检查(它从来自 Spring 框架 @RestController).

我正在检查 accountId(它是一个字符串)是否不为 null、空字符串并且不能包含任何空格。

@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.
    }
}


在我的服务 class 的集成测试中:

@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 return HTTP 200 而不是 HTTP 400?

我需要 accountId 始终是字符串而不是数字...

我需要在我的 Cucumber 步骤中添加什么才能使它们成为 HTTP 400?

您没有抛出任何异常,您只是记录了一个错误。您有什么理由期待 400?

是的,在 logger.error() 语句之后立即抛出自定义异常是解决方案。

我发现,由于我使用 openapi 自动生成这些模型和 REST 控制器,在模式 yaml 文件中,我可以将 accountId 指定为“必需”,以便在幕后进行这些验证发生。

感谢大家提供所有有用的反馈!