lundi 24 septembre 2018

C# unit testing try statement in program.cs Main

I have my project that start like below, I want to create a unit test to validate what happens when either appsetting.Environment.json doesn't exist or the DataSource:JsonPath file doesn't exist.

I am using xUnit but just getting into it

With this scenario it should throw FileNotFoundException and exit.

internal class Program
{
    private static int Main(string[] args)
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "Production"}.json", optional: true)
            .Build();

        try
        {
            Log.Information($"{DateTime.Now.ToLongTimeString()} Starting...");

            var jsonFileName = Configuration["DataSource:JsonPath"];
            if (!File.Exists(jsonFileName)) throw new FileNotFoundException(jsonFileName);

            //code if file exist...
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Terminated unexpectedly");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire