SpecFlow - Creating First Test



We shall now create a file in the class library which performs subtraction of two numbers.

using System;
namespace ClassLibrary2 {
   public class Class1 {
      public int Number1 { get; set; }
      public int Number2 { get; set; }
      public int Subtraction(){
         return Number1 - Number2;
      }
   }
}

Feature File Implementation

File Implementation

Step Definition File Implementation

The corresponding Step Definition file of the above Feature file, along with usage of Class1 to perform subtraction.

using ClassLibrary2;
using FluentAssertions;
using TechTalk.SpecFlow;
namespace SpecFlowCalculator.Specs.Steps { 
[Binding]
   public sealed class CalculatorStepDefinitions {
      private readonly ScenarioContext _scenarioContext;
      
      //instantiating Class1
      private readonly Class1 _calculator = new Class1();
      private int _result;
      public CalculatorStepDefinitions(ScenarioContext scenarioContext) {
         _scenarioContext = scenarioContext;
      }
      [Given("the first number is (.*)")]
      public void GivenTheFirstNumberIs(int number){
         _calculator.Number1 = number;
      }
      [Given("the second number is (.*)")]
      public void GivenTheSecondNumberIs(int number){
         _calculator.Number2 = number;
      }
      [When("the two numbers are subtracted")]
      public void WhenTheTwoNumbersAreSubtracted(){
         _result = _calculator.Subtraction();
      }
      [Then("the result should be (.*)")]
      public void ThenTheResultShouldBe(int result){
         _result.Should().Be(result);
      }
   }
}

Executing the Test

Build the above solution, then execute the test after we obtain the build succeed message from Test → Test Explorer.

Select the SpecFlowProject1 feature and click on Run All tests in View.

SpecFlowProject

The result shows as 1 Passed along with execution duration. Click on the option Open additional output for this result to get result details.

Execution Duration

The execution result for each test step is displayed.

Execution Result

All the steps in the Feature File get executed along with status as done. Also, the corresponding methods in the Step Definition File get displayed with the execution duration.

Advertisements