How can I use IConfiguration from my integration tests?

The appsettings.json file is just in my test project root, do you know an easy way to get the current project path so that I don't have to hard-code that value

Set the Build Action property of the file to Content so it will copy to output directory so it is moved to the bin when testing and then you can use the original config code with the .SetBasePath(Directory.GetCurrentDirectory())

public async Task GetUserShouldReturnOk() {
    var userId = new Guid();
    var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

    var controller = new MyController(
        new MyRepository(configuration));

    var result = await controller.GetUser(userId);

    Assert.IsType<OkResult>(result);
}

I think it's better to use dependency injection in your test project; for future use.

In your test project:

  1. Add a new appsettings.json file to your test project with all the configurations you need.
  2. Install the package: Microsoft.Extensions.DependencyInjection.
  3. Create a class for the test setup; for instance TestSetup.cs.

    public class TestSetup
    {
        public TestSetup()
        {
            var serviceCollection = new ServiceCollection();
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(
                     path: "appsettings.json",
                     optional: false,
                     reloadOnChange: true)
               .Build();
            serviceCollection.AddSingleton<IConfiguration>(configuration);
            serviceCollection.AddTransient<MyController, MyController>();
    
            ServiceProvider = serviceCollection.BuildServiceProvider();
        }
    
        public ServiceProvider ServiceProvider { get; private set; }
    }
    
  4. In your test class; I am using Xunit

    public class MyControllerTest: IClassFixture<TestSetup>
    {
        private ServiceProvider _serviceProvider;
        private MyController _myController;
    
        public MyControllerTest(TestSetup testSetup)
        {
           _serviceProvider = testSetup.ServiceProvider;
           _myController = _serviceProvider.GetService<MyController>();
        }
    
        [Fact]
        public async Task GetUserShouldReturnOk()
        {
            var result = await _myController.GetUser(userId);
            Assert.IsType<OkResult>(result);
        }
    
    }