Ramesh_NS
Ramesh_NS

Reputation: 25

How to pass optional parameter in Specflow in C#

I have the below steps in feature file

When I add employee with vendor 'vendorname'
And I add employee with vendor 'vendorname' and client 'clientname'

I want these two steps in a single step definition where client name can be optional. I can able to achieve this using two step definition but it will duplicate the code.

Upvotes: 2

Views: 4799

Answers (4)

Dmitry Gusarov
Dmitry Gusarov

Reputation: 1639

You can have only one optional parameter at the end of line. Using non-capturing groups

[When(@"I add employee with vendor '(.*)'(?: and client '(.*))'")]
public void IAddEmptoyee(string vendorName, string clientName = null)
{
}

Upvotes: 0

Stefan
Stefan

Reputation: 1926

Well, i guess you can do a few things depending on what you want to achieve or how you would like your code looks like. For now i got one thing on my mind.

For instance, instead of:

When I add employee with vendor 'vendorname'
And I add employee with vendor 'vendorname' and client 'clientname'

you can write next:

When I add employee with vendor 'vendorname' and client 'clientname'

or, apply the same as Fran proposed:

When I add an employee with the following information
| vendor     | client     |
| vendorname | clientname |

And then when you set up your input parameters in your steps in .feature files, you can pick any predefined string or value which you will query in your step definition file (with if or switch statement).

Upvotes: 0

Andreas Willich
Andreas Willich

Reputation: 5835

Optional parameters are not supported by SpecFlow.
You need separate steps for that.

But we are welcoming PRs for that: https://github.com/techtalk/SpecFlow/issues/316

Upvotes: 2

Fran
Fran

Reputation: 6520

So you want to write something like this

When I add an employee with the following information
| vendor     | client     |
| vendorname | clientname |

This will generate a step definition with a Table parameter.

you can spin through the table yourself or use the helper functions of table CreateInstance, CreateInstance<>, CreateSet, CreateSet<> to map the table to objects in your test.

Upvotes: 0

Related Questions