App.config for Xunit

If your code assumes they are in the app.config, then xUnit.net supports having them wired up in there by providing one (typically when the tests are in a DLL file, this means you get a AssemblyName.dll.config file in the project outputs which the runner loads as the settings if it exists at load time).

Obviously no harm to use the DI principle to remove such dependencies in the first place, but I'd say don't go messing with code before you actually get it under test first.

To keep it DRY, put the app.config in a central place and add it as a link (via the arrow on the Open button in the dialog). (Yes, there's lots not to like about that - use only if you feel its the least evil approach.)


One thing to look out for is that changes don't get reloaded in the GUI runner unless you ask for the assembly to be reloaded.


From perspective more complex projects & team work, I recommend:

  1. separate .config file for xUnit project (it takes advantage of independent configuration & logging for running tests)
  2. set-up Dependency Injection together with .config reading for xUnit project alone

Our team is using this pattern of xUnit init & dispose:

    public class MyTest : IDisposable
    {
        public IServiceProvider Services { get; private set; }
        public MyProjectOptions Options { get; private set; }
        public Logger Logger { get; private set; }

        private void Configure()
        {
            // appsettings.workspace.json for custom developer configuration
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile("appsettings.workspace.json", optional: true)
                .Build();

            Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.LiterateConsole()
                .WriteTo.RollingFile("logs/{Date}-log.txt")
                .CreateLogger();

            Options = configuration.GetSection("MyProject").Get<MyProjectOptions>();

            var services = new ServiceCollection();
            services.AddSingleton<ILogger>(s => Logger);
            // other DI logic and initializations ...
            //services.AddTransient(x => ...);

            Services = services.BuildServiceProvider();
        }

        public MyTest()
        {
            Configure();

            // ... initialize data in the test database ...
            var data = Services.GetService<TestDataService>();
            data.Clean();
            data.SeedData();
        }

        public void Dispose()
        {
            // ... clean-up data in the test database ...
            var data = Services.GetService<TestDataService>();
            data.Clean();
        }
    }

Tags:

C#

Xunit.Net