Search code examples
nunitplaywright

NUnit - how to test operation twice using custom setting each time


I would like to know how to test propertly via NUnit same operation. Each call should set parameter to static property. I am looking for similiar TestCase implementation.

Usage:

[DesktopTest, MobileTest]
public async Task ShouldA()
{
}

NUnit is using Playwright framework. Intention is to use different viewport size without passing parameter like

[TestCase("desktop")]
[TestCase("mobile")]
public async Task ShouldA(string device)
{
}

My current implementation of DesktopTest

public class DesktopTestAttribute : TestCaseAttribute
{
   public DesktopTestAttribute() : base()
   {
      TestManager.SetDevice("desktop"); // static class
   }
}

However constructor is followed by MobileTest constructor which override device.

What is proper way to not set mobile device if I run desktop target?


Solution

  • You could use TestFixture inheritance:

    public class TestManager
    {
        public static void SetDevice(string device) => Device = device;
    
        public static string Device { get; private set; }
    }
    
    public abstract class BaseFixture
    {
        protected BaseFixture(string device)
        {
            TestManager.SetDevice(device);
    
            this.device = device;
        }
    
        [Test]
        public void ShouldA() => Assert.That(TestManager.Device, Is.EqualTo(device));
    
        private string device;
    }
    
    [TestFixture]
    public class DesktopTest: BaseFixture
    {
        public DesktopTest(): base("desktop") { }
    }
    
    [TestFixture]
    public class MobileTest: BaseFixture
    {
        public MobileTest(): base("mobile") { }
    }