Search code examples
c#seleniumxunitappsettings

Why can't my .net core xunit test find my appsettings.json?


I am new to testing/development. I have created a x unit test project in .net core for testing the UI of my website using selenium. My file structure looks like this file

This is my appsettings.json:

{
  "Base_Url": "https://pretendurl/",
  "AllowedHosts": "*"
}

This is my test class:

using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using Microsoft.Extensions.Configuration;
using System.Configuration;

namespace XUnitTestProject1.UI.Tests
{
    public class HomePageShould
    {
        [Fact]
        public void LoadHomepage()
        {

            using IWebDriver driver = new ChromeDriver();
            var settings = new ConfigurationBuilder()
               .AddJsonFile("appsettings.json")
               .Build();

            var homeUrl = settings["Base_Url"];
            
            driver.Navigate().GoToUrl(homeUrl);

        }
    }
}

I get this error: The configuration file 'appsettings.json' was not found and is not optional. My test project is in a separate repo from the system I am testing.


Solution

  • You need to update the XUnitTestProject1.UI.Tests.csproj to export your appsettings to the build folder.

      <ItemGroup>
        <None Update="appsettings.Test.json" CopyToOutputDirectory="PreserveNewest" />
      </ItemGroup>
    

    You should reate a separate appsettings.Test.json file in your test project with your test settings, and the code above will copy it to the build folder.