I'm encountering a System.NullReferenceException
in my Playwright when trying to navigate to a URL fetched from my appsettings.json file. The error occurs at the line await page.GoToAsync(baseUrl)
.
The baseUrl
is correctly set in the appsettings.json file, and I've verified that it is being read correctly.
Here is my code:
public static IPlaywright playwright;
public static string baseUrl;
[BeforeTestRun]
public static async BeforetestRun()
{
playwright = await Playwright.CreateAsync();
baseUrl = CongigReader.GetBaseUrl["BaseURL"];
}
[BeforeScenario]
public async Task BeforeScenario()
{
var browser = await playwright.Chromium.LaunchAsync(new
BrowserTypeLaunchOptions {
Headless = false,
Args=new[] {"--disable-features"}
});
var context = await browser.NewContextAsync((new
BrowserNewContextOptions
{ IgnoreHTTPSErrors = false
});
var page = await context.NewPageAsync();
await page.GoToAsync(baseUrl);
}
ConfigReader class:
public static class ConfigReader
{
public static IConfiguration _config;
public static IConfiguration ConfigBuilder()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
_config = builder.Build();
return _config;
}
public static string GetBaseUrl(string value)
{
return ConfigBuilder[value];
}
}
Feature File
Feature: Login
@Login
Scenario: Login operation
Given I navigate to the application url
When I enter the login details
Then I should see application dashboard
My appsettings.json file is as follows:
{
"BaseURL": "my url"
}
Even though my baseUrl
is correct and Playwright and browser instance are properly initialized, I keep getting this error:
System.NullReferenceException: Object reference not set to an instance of an object.
How can I resolve this issue?
I even tried passing the baseURL
directly instead of fetching it from appsettings.json, still got the same error.
Stack Trace is as follows:
2025-03-18T13:32:46.7221415Z Stack Trace:
2025-03-18T13:32:46.7221827Z at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.FireEvents(HookType hookType)
2025-03-18T13:32:46.7222293Z at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.FireScenarioEvents(HookType bindingEvent)
2025-03-18T13:32:46.7222748Z at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnStepEnd()
2025-03-18T13:32:46.7223240Z at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(IContextManager contextManager, StepInstance stepInstance)
2025-03-18T13:32:46.7223819Z at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.Step(StepDefinitionKeyword stepDefinitionKeyword, String keyword, String text, String multilineTextArg, Table tableArg)
2025-03-18T13:32:46.7224379Z at TechTalk.SpecFlow.TestRunner.Given(String text, String multilineTextArg, Table tableArg, String keyword)
2025-03-18T13:32:46.7224939Z at PlaywrightAutomation.Features.LoginFeature.LoginOperation() in D:\a\1\s\PlaywrightAutomation\Features\Login.feature:line 5