How do I test multiple browsers with selenium and a single NUnit suite and keep it DRY?

前端 未结 5 2020
逝去的感伤
逝去的感伤 2021-02-14 17:41

I\'m looking for a way to reuse one NUnit test suite without duplicating the entire suite for each browser. It seems like I would need a new fixture for each browser. Can I send

5条回答
  •  日久生厌
    2021-02-14 18:04

    Here is an example unit test using a custom XUnit DataAttribute to provide the Driver to the test

    using OpenQA.Selenium;
    using SeleniumPageObjectsPatternExample.Attributes;
    using SeleniumPageObjectsPatternExample.PageObjects;
    using Xunit;
    using Xunit.Extensions;
    
    public class HomepageTests 
    {
        [Theory]
        [Browser(Type.Firefox)]
        [Browser(Type.GoogleChrome)]
        public void HomepageLinksToBlogPage(IWebDriver webDriver)
        {
            // arrange 
            var expected = "some expected value";
    
            // act
            var homepage = new HomePage(webDriver, true);
    
            // assert
            Assert.True(homepage.BlogLink.Displayed);
            Assert.Equal(expected, homepage.Header.Text);
        }
    }
    

    Here is the custom DataAttribute

    using System.Reflection;
    using OpenQA.Selenium;
    using SeleniumPageObjectsPatternExample.WebDriver;
    using Xunit.Extensions;
    
    public class BrowserAttribute : DataAttribute
    {
        private IWebDriver WebDriver { get; set; }
    
        public BrowserAttribute(Type browser)
        {
            this.WebDriver = WebDriverFactory.Create(browser);
        }
    
        public override IEnumerable GetData(MethodInfo methodUnderTest, System.Type[] parameterTypes)
        {
            return new[] { new[] { this.WebDriver } };
        }
    }
    

    Using this WebDriverFactory

    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium.Firefox;
    
    using Type = SeleniumPageObjectsPatternExample.Attributes.Type;
    
    public class WebDriverFactory
    {
        public static IWebDriver Create(Type browser)
        {
            IWebDriver webDriver;
    
            switch (browser)
            {
                case Type.Firefox:
                    webDriver = new FirefoxDriver();
                    break;
                case Type.GoogleChrome:
                    webDriver = new ChromeDriver();
                    break;
                default:
                    webDriver = new ChromeDriver();
                    break;
            }
    
            webDriver.Manage().Window.Maximize();
    
            return webDriver;
        }
    }
    

    And the browser type enum

    public enum Type
    {
        Firefox,
        GoogleChrome
    }
    

    I would advise you change the name of the enum from Type to something else...

提交回复
热议问题