Home > front end >  SpecFlow - one featuretwo data sets
SpecFlow - one featuretwo data sets

Time:01-28

I have two data sets, I want to use them depending on which machine the tests will be run on. How to do this in specflow?

Scenario: The user logs in using the confirmed account When Logging in to the account: user1/user2 Then Login succesful

If the tests run on machine1 then i use user1 account, if they run on machine 2 i use user2 account. How to do it?

CodePudding user response:

There are a couple of ways to accomplish this. The easiest way might be to store usernames in a Dictionary where the key is the hostname, and the value is the username.

This involves 3 parts:

  1. Create a config class

    public class TestConfiguration
    {
        private readonly Dictionary<string, string> passwords;
        private readonly Dictionary<string, string> usernames;
    
        /// <summary>
        /// Returns the test password based on the current machine
        /// </summary>
        public string Password => passwords[Environment.MachineName];
    
        /// <summary>
        /// Returns the test username based on the current machine
        /// </summary>
        public string Username => usernames[Environment.MachineName];
    
        public TestConfiguration()
        {
            passwords = new Dictionary<string, string>()
            {
                { "hostname1", "password1" },
                { "hostname2", "password2" }
            };
            usernames = new Dictionary<string, string>()
            {
                { "hostname1", "username1" },
                { "hostname2", "username2" }
            };
        }
    }
    
  2. Register this with the SpecFlow dependency injection framework

    [Binding]
    public class SpecFlowHooks
    {
        private readonly IObjectContainer container;
    
        public SpecFlowHooks(IObjectContainer container)
        {
            this.container = container;
        }
    
        [BeforeScenario]
        public void BeforeScenario()
        {
            var config = new TestConfiguration();
    
            container.RegisterInstanceAs(config);
        }
    }
    
  3. Use TestConfiguration in your step definitions

    [Binding]
    public class LoginSteps
    {
        private readonly TestConfiguration config;
    
        public LoginSteps(TestConfiguration config)
        {
            this.config = config;
        }
    
        [Given(@"the user is logged in")]
        public void GivenTheUserIsLoggedIn()
        {
            // Log in using config.Username and config.Password
        }
    }
    

If you need the user information in any other step definition classes, simply add a TestConfiguration config parameter to the constructor of that class. See Context Injection for more information on how to use dependency injection with SpecFlow.

  •  Tags:  
  • Related