Search code examples
c#specflowextentreports

How is best to introduce a Base class for Specflow? This one isn't working


anyone know how to create a baseclass so that step definitions can inherit? Need to intergrate extent reports in a [setup] for it. I have tried this one but does not output

public class BaseClass(){
[Before]
public class void BeforeTests(){

console.writeline("This runs before the tests");

//Extent reports setup code here
}
[After]
public class void AfterTests(){

//Extent reports flush code here
console.writeline("This runs after the tests");
}
}
[Bindings]
public class StepDefinitionFile: BaseClass
{
}

Thanks


Solution

  • Since you are just using hooks, you do not need a base class. Instead, create a class that specializes in the Extend Report logic. No need to inherit from this class in your other step definitions:

    [Binding]
    public class ExtentReports
    {
        [Before]
        public void BeforeScenario(ScenarioInfo scenario)
        {
            // Extent report logic
        }
    
        [After]
        public void AfterScenario(ScenarioInfo scenario)
        {
            // Extent report logic
        }
    }
    

    If you need Extent report logic in multiple step definition classes, consider creating another class and use context injection to get the object:

    public class ExtentReportUtils
    {
        // common Extent Report logic and methods here
    }
    
    [Binding]
    public class SpecflowHooks
    {
        IObjectContainer container;
    
        public SpecflowHooks(IObjectContainer container)
        {
            this.container = container;
        }
    
        [Before]
        public void Before()
        {
            var utils = new ExtentReportUtils();
    
            container.RegisterInstanceAs(utils);
        }
    }
    

    And to use it in a step definition (or even the ExtentReports class above):

    [Binding]
    public class YourSteps
    {
        ExtentReportUtils extentUtils;
    
        public YourSteps(ExtentReportUtils extentUtils)
        {
            this.extentUtils = extentUtils;
        }
    
        [Given(@"...")]
        public void GivenX()
        {
            extentUtils.Foo(...);
        }
    }