1

I am trying to use the "[OneTimeSetUp]" attribute in my TestFixture but I am receiving a NullReferenceException on "Page"? I am using Microsoft.Playwright.NUnit. I can use the "[Setup]" attribute fine but just not the "[OneTimeSetup]"?

I am trying to use the [OneTimeSetup] to login to my site and then store the authentication using Page.Context.StorageStateAsync and then I want to use "[OneTimeTearDown]" to logout again so that I can re run the tests. If I use [Setup] then I lose the efficiency of storing the authenticaion.

I had a method which used the [Setup] attribute just fine so I simply changed this to use the [OneTimeSetup] attribute instead and started to get a null exception.

Below is an example of code which contains my issue.


using System.Data.SqlTypes;
using Microsoft.Playwright;
using Microsoft.Playwright.NUnit;
    
    namespace PlaywrightTests
    {   
        [Parallelizable(ParallelScope.Fixtures)]
        public class Tests1V2 : PageTest
        {
            private string site = "https://google.co.uk/";
    
            public override BrowserNewContextOptions ContextOptions()
            {
                var contextOptions = new BrowserNewContextOptions();
                contextOptions.StorageStatePath = "state.json";
                if (Environment.GetEnvironmentVariable("width") != null)
                {
                    int result = Int32.Parse(Environment.GetEnvironmentVariable("width")!);
                    contextOptions.ViewportSize = new ViewportSize { Width = result };
                }
                return contextOptions;
            }
    
            [SetUp]
            public async Task setup()
            {
                var page = Page;
                await page.GotoAsync(site);
            }
    
            [OneTimeSetUp]
            public async Task oneTimeSetUp()
            {
                var page = Page;
                await page.GotoAsync(site);
            }
    
            [Test]
            public async Task AALoginTest1()
            {
                //var mainPage = new MainPage(Page);
                //var checkContact = await mainPage.checkLoggedIn();
                //Assert.IsTrue(checkContact);
            }
}
}
user500770
  • 11
  • 2

1 Answers1

0

I had this same issue and finally solved it by creating a new Driver during my OneTimeSetUp. I would suggest checking out this post for the driver code: Microsoft.Playwright.PlaywrightException:Connection closed (connection disposed) - getting this error using PoM Playwright c#, Visual studio 2022

Then your set up will look like this:

public static Driver _driver;

        [OneTimeSetUp]
        public async Task Init()
        {
            _driver = new Driver();
            await _driver.Page.GotoAsync(site);
        }
desertnaut
  • 57,590
  • 26
  • 140
  • 166