September 08, 2020

DI/CI Specflow



Dependency Injection-

Dependency Injection is a techniques whereby one object supplies the dependency of another object. Dependency is an object that is used as a service.

For example- At left hand side image , Chef says I need objects a and b. The waiter does not know anything about a and b . Dependency injection acts like a window between waiter and Chef. Objects are in DI that is hidden. Window is going to create object a and b but you cant see that. At right hand side , you can see waiter gives the object a and b to the Chef.


Context Injection-

SpecFlow supports a very simple dependency framework that is able to instantiate and inject class instances for scenarios. This feature allows you to group the shared state in context classes, and inject them into every binding class that needs access to that shared state.

To use context injection:

Create your POCOs (Plain old C# Object)(simple .NET classes) representing the shared data.

Define them as constructor parameters in every binding class that requires them.

Save the constructor argument to instance fields, so you can use them in the step definitions.

In this example we define a POCO for holding the data of a person and use it in a given and a then step that are placed in different binding classes.

public class PersonData // the POCO for sharing person data
{ 
  public string FirstName;
  public string LastName;
}

[Binding]
public class MyStepDefs
{
  private readonly PersonData personData;
  public MyStepDefs(PersonData personData) // use it as ctor parameter
  { 
    this.personData = personData;
  }
  
  [Given] 
  public void The_person_FIRSTNAME_LASTNAME(string firstName, string lastName) 
  {
    personData.FirstName = firstName; // write into the shared data
    personData.LastName = lastName;
    //... do other things you need
  }
}

Scenario Context-

You may have at least seen the ScenarioContext from the code that SpecFlow generates when a missing step definition is found: ScenarioContext.Pending();

ScenarioContext provides access to several functions, which are demonstrated using the following scenarios

Feature Context-

SpecFlow provides access to the current test context using both FeatureContext and the more commonly used Scenario Context. 
Feature Context persists for the duration of the execution of an entire feature, whereas Scenario Context only persists for the duration of a scenario.

No comments:

Post a Comment

Please let me know if you have any doubts.

Key concepts in Pipeline

 1. Agent- To build your code or deploy your software using azure pipelines, you need at least one agent. Two types of agent- Microsoft host...