首页 > 解决方案 > 如何防止数字和空格在 Java 中的 Cucumber 测试中传递字符串?

问题描述

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

使用 Java 1.8 和 SpringWebFlux,我在我的服务类中创建了以下检查(从 Spring Framework 的 HTTP POST 请求中获取值@RestController)。

我正在检查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 始终是一个字符串,而不是一个数字......

为了使这些成为 HTTP 400,我需要在 Cucumber 步骤中添加什么?

标签: javacucumberspring-webflux

解决方案


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


推荐阅读