Search code examples
json.netunit-testingappsettingsxunit.net

ConfigurationBuilder.AddJsonFile uses wrong json file every other time


I have a .Net 8.0 Unit test project. This project is part of a solution that contains the application projects as well.

As part of the test setup a ConfigurationBuilder is used.

var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json", optional: true);
var configuration = configurationBuilder.Build();

When running the tests repeatedly, the configuration loads the (incorrect) appSettings.json file from the application project, next time the (correct) appSettings.json file from the test project, then again the incorrect file, then again the correct file, etc.

The application appSettings.json file does not contain a setting that is needed in the test project.

I tried several solutions to have the ConfigurationBuilder load the correct settings file all the time.

  • Creating a PhysicalFileProvider, and using ConfigurationBuilder.SetFileProvider
  • Creating a PhysicalFileProvider, and specifying that when calling AddJsonFile
  • Using SetBaseDirectory

All of the above methods fail to solve the problem. My question is: why is ConfigurationBuilder alternating between two appSettings.json file? How can I stop it from doing that?


Solution

  • I have several questions

    Does your projects output folder same? If so can you replace your test appsettings.json with appsettings.test.json etc.

    TestProject.csproj

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

    AgentTest.cs

    public class AgentTests : BaseTest
    {
        static IConfiguration Configuration {get; set;}
    
        public AgentTests() : base(false)
        {
    
        }
    
        [SetUp]
        public void Setup()
        {
           Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.test.json").Build();
    
        }
    
        [Test]
        public async Task Can_Get_AgentById()
        {
           // Arrange
    
           int agentId = 350;
           IAgentRepository agentRepo = new AgentService(Configuration);
    
           // Act       
    
           var result = await agentRepo.GetAgentById(agentId);
    
           // Assert
         
           Assert.That(result is not null);
       }
    }
    

    I am able to use like this.

    Let me know more details if this answer not covering your problem.