Yogiraj
Yogiraj

Reputation: 273

How to pass List of strings from Cucumber Scenario

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

Upvotes: 24

Views: 100763

Answers (7)

cleuton
cleuton

Reputation: 165

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.

Upvotes: 0

Sheikh Aafaq Rashid
Sheikh Aafaq Rashid

Reputation: 199

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)

Upvotes: 2

Mai Hữu Lợi
Mai Hữu Lợi

Reputation: 569

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));
}

Upvotes: 2

SUMIT
SUMIT

Reputation: 575

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

Upvotes: 19

Ranjith&#39;s
Ranjith&#39;s

Reputation: 4730

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
 }

Upvotes: 13

diabolist
diabolist

Reputation: 4099

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

Upvotes: -5

Daniel Fintinariu
Daniel Fintinariu

Reputation: 2793

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

Upvotes: 1

Related Questions