dev_in_training
dev_in_training

Reputation: 433

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.

Upvotes: 3

Views: 3216

Answers (2)

Adi Šoše
Adi Šoše

Reputation: 86

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.

Upvotes: 6

Steve Harris
Steve Harris

Reputation: 5109

Change the 'Copy to output folder' property of the json file in VS. It needs to be copied to the output folder where the app will run.

Upvotes: 1

Related Questions