How to pass List of strings from Cucumber Scenario
Asked Answered
P

7

20

I need to pass the List of strings from cucumber scenario which works fine as below

Scenario Outline: Verify some scenario 
Given something
When user do something 
Then user should have some "<data>" 
Examples: Some example
|data|
|Test1, Test2, Test3, Test4|

In the step definition I use List to retrieve the values of something variable. But when one of the value of data variable contains comma(,) e.g. Tes,t4 it becomes complex,since it considers "Tes" and "t4" as two different values

 Examples: Some example
 |something|
 |Test1, Test2, Test3, Tes,t4|  

So is there any escape character that i can use or is there is there any other way to handle this situation

Permanence answered 11/7, 2017 at 11:53 Comment(4)
Try escaping the required comma with '\'...Foothold
i had tried this already, it doesn't workPermanence
Can you add the step definition for this? I think you need to use the Transform annotation to create your own custom logic for escaping the comma. Split it with using a regular expression for ignoring comma immediately after the escape character...Foothold
Take a look at this: blog.dupplaw.me.uk/articles/2019-07/…Psychotomimetic
E
18

Found an easy way. Please see the below steps.

  • Here is my feature file.

    feature file

  • Here is the corresponding code to map feature step with code.

    code for the corresponding feature

  • Oh yes. Result is important. You can see the debug view.

    result in the debug view

Englis answered 23/11, 2018 at 11:36 Comment(3)
which version of cucumber you are using?Vaginectomy
Can you provide some references for this List conversion?Rheostat
This is barely visible, please use code snippetsChishima
C
11

This should work for you:

Scenario: Verify some scenario 
Given something
When user do something 
Then user should have following
| Test1 |
| Test2 |
| Test3 |
| Tes,t4| 

In Step definitions

Then("^user should have following$")
 public void user_should_have_following(List<String> testData) throws Throwable {
 #TODO user your test data as desired
 }
Chesterfieldian answered 11/7, 2017 at 14:40 Comment(0)
V
2

In Transformer of TypeRegistryConfigurer, you can do this

@Override
public Object transform(String s, Type type) {
    if(StringUtils.isNotEmpty(s) && s.startsWith("[")){
        s = s.subSequence(1, s.length() - 1).toString();
        return Arrays.array(s.split(","));
    }
    return objectMapper.convertValue(s, objectMapper.constructType(type));
}
Vonnie answered 23/10, 2019 at 5:48 Comment(0)
R
2

Examples:

Colors color-count
Red, Green 5
Yellow 8
def function("{colors}"):
context.object.colors = list(colors.split(","))
for color in context.object.colors:
    print(color)
Ramon answered 4/8, 2022 at 9:35 Comment(0)
L
1

Try setting the Examples in a column, like this:

| data   |
| Test1  |
| Test2  |
| Test3  |
| Tes,t4 |

This will run the scenario 4 times, expecting 'something' to change to the next value. First 'Test1', then 'Test2', etc.

In the step definition you can use that data like so:

Then(/^user should have some "([^"]*)"$/) do |data|
  puts data
end

If you want to use |Test1, Test2, Test3, Tes,t4|, change the ',' to ';' ex: |Test1; Test2; Test3; Tes,t4| and in the step definition split the data:

data.split("; ") which results in ["test1", "test2", "test3", "te,st"]

Converting the data to a List (in Java):

String test = "test1; test2; test3; tes,t4";
String[] myArray = test.split("; ");
List<String> myList = new ArrayList<>();
for (String str : myArray) {
    myList.add(str);
}
System.out.print(myList);

More on this here

Litigious answered 11/7, 2017 at 12:22 Comment(5)
I need all these values together to execute a single scenario, this will not work in my case.Permanence
You can separate |Test1, Test2, Test3, Tes,t4| with ';', and you would get |Test1; Test2; Test3; Tes,t4|. Now, in the step definition you can split the data like so: data.split("; ") and you will get an array of of 4 elements including the troublesome "Tes,t4" => result is: ["test1", "test2", "test3", "te,st"]Litigious
I tried this it doesn't work, since i am using List in step definition to retrieve these values. List considers comma(,) as a delimeter. hence it results in same issue.Permanence
String data = "test1; test2; test3; tes,t4"; String[] myArray = test.split("; "); List<String> myList = new ArrayList<>(); for (String str : myArray) { myList.add(str); } System.out.print(myList);Litigious
More on this javadevnotes.com/java-array-to-list-examples if Java is what you need.Litigious
S
0

You need to pass a list of strings from feature to steps code. Ok. Let me show you an example. This is my feature file:

    Feature: Verificar formas de pagamento disponíveis para o cliente

  Scenario Outline: Cliente elegível para múltiplas formas de pagamento
    Given um cliente com <tempo_cliente> meses de cadastro, situação de crédito "<situacao_credito>", valor do último pedido <valor_ultimo_pedido> e último pagamento <valor_ultimo_pagamento>
    And um pedido com valor de entrada <valor_entrada> e valor total <valor_pedido>
    When verificar as formas de pagamento disponíveis
    Then as formas de pagamento disponíveis devem ser <formas_pagamento>

    Examples:
      | tempo_cliente | situacao_credito | valor_ultimo_pedido | valor_ultimo_pagamento | valor_entrada | valor_pedido | formas_pagamento                                         |
      | 6             | boa              | 500                 | 250                    | 100           | 500          | Pagamento à vista, Pagamento em 2 vezes com juros    |
      | 12            | boa              | 1500                | 750                    | 300           | 1500         | Pagamento à vista, Pagamento em 2 vezes com juros, Pagamento em 3 vezes sem juros, Pagamento em 6 vezes sem juros |
      | 7             | regular          | 800                 | 400                    | 200           | 1000         | Pagamento à vista, Pagamento em 2 vezes com juros |

As you can see, I have a table. Pay attention to the Then step:

Then as formas de pagamento disponíveis devem ser <formas_pagamento>

This will pass the value of column "formas_pagamento" in the table. Note that the column values can be one or multiple strings. And you want to capture this on your @Then step. This is my Step definition:

@Then("^as formas de pagamento disponíveis devem ser (.*)$")
public void as_formas_de_pagamento_disponíveis_devem_ser(String resultado) {
    List<String> formasEsperadas = Arrays.asList(resultado.split("\\s*,\\s*"));
    assertEquals(formasEsperadas, formasPagamentoDisponiveis);
}

You will receive as a regex that repeats itself and declare it as string argument. Then you need to split each string and transform the resulting array into a list.

Shrievalty answered 27/2, 2024 at 21:38 Comment(0)
L
-5

Don't put the data in your scenario. You gain very little from it, and it creates loads of problems. Instead give your data a name and use the name in the Then of your scenario

e.g.

 Then the user should see something

Putting data and examples in scenarios is mostly pointless. The following apply

  1. The data will be a duplication of what should be produced
  2. The date is prone to typos
  3. When the scenario fails it will be difficult to know if the code is wrong (its producing the wrong data) or the scenario is wrong (you've typed in the wrong data)
  4. Its really hard to express complex data accurately
  5. Nobody is really going to read your scenario carefully enough to ensure the data is accurate
Liliuokalani answered 13/7, 2017 at 10:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.