0

I am writing Unit Tests using NUnit. This is my Class under test looks like

public class CustomerService
{
 private readonly IConfiguration _configuration;

 // ctor
 CustomerService(IConfiguration configuration)
 {
 }
}

Unit Test of the above class.

public class CustomerServiceTests
{
   private readonly IConfiguration _configuration;

   CustomerServiceTests()
   {
      _configuration =  GetConfiguration();
   }

   public static IConfiguration GetConfiguration(string outputPath="")
    {
        return new ConfigurationBuilder()
                .SetBasePath(outputPath)
                .AddJsonFile("appsettings.json", optional: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .Build();
    }

}

Now I need to get the path of the appsettings.json directory which is present in the StartUp (API) project

This is my how project directory looks like

  • CustomerProject

    -customer.api

    -customer.services

    -customer.services.test

How do I get the path of customer.api project which is containing the appsettings.json?

Kgn-web
  • 7,047
  • 24
  • 95
  • 161

2 Answers2

0

You can do:

public static string GetProjectPath(Type startupClass)
{
    var assembly = startupClass.GetTypeInfo().Assembly;
    var projectName = assembly.GetName().Name;
    var applicationBasePath = AppContext.BaseDirectory;
    var directoryInfo = new DirectoryInfo(applicationBasePath);
    do
    {
       directoryInfo = directoryInfo.Parent;

       var projectDirectoryInfo = new DirectoryInfo(directoryInfo.FullName);
       if (projectDirectoryInfo.Exists)
       {
          var projectFileInfo = new FileInfo(Path.Combine(projectDirectoryInfo.FullName, projectName, $"{projectName}.csproj"));
          if (projectFileInfo.Exists)
          {  
              return Path.Combine(projectDirectoryInfo.FullName, projectName);
          }
       }
    } while (directoryInfo.Parent != null);
}

Call it like:

var path = GetProjectPath(typeof(StartUp));
kovac
  • 4,945
  • 9
  • 47
  • 90
0

Instead of injecting IConfiguration into the controller you can do yourself a big favor by following the IOptions pattern. Then you can easily mock out the configuration that you want to pass to the controller in a unit test, without having to integration test with you appsettings.

See Options pattern in ASP.NET Core

There are also lots of example on how to set your IOptions in you unit tests, like this one Here

In general, if your unit tests needs to depend on some secondary artifact of the unit under test, you are integration testing rather than unit testing. Those tests tend to be really hard to maintain an write.

GlennSills
  • 3,977
  • 26
  • 28