How to Unit Test Startup.cs in .NET Core

前端 未结 3 1912
一向
一向 2020-12-14 01:20

How do people go about Unit Testing their Startup.cs classes in a .NET Core 2 application? All of the functionality seems to be provided by Static extensions methods which a

3条回答
  •  星月不相逢
    2020-12-14 01:48

    This approach works, and uses the real MVC pipeline, as things should only be mocked if you need to change how they work.

    public void AddTransactionLoggingCreatesConnection()
    {
         var servCollection = new ServiceCollection();
    
        //Add any injection stuff you need here
        //servCollection.AddSingleton(logger.Object);
    
        //Setup the MVC builder thats needed
        IMvcBuilder mvcBuilder = new MvcBuilder(servCollection, new Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager());
    
        IEnumerable> confValues = new List>()
        {
            new KeyValuePair("TransactionLogging:Enabled", "True"),
            new KeyValuePair("TransactionLogging:Uri", "https://api.something.com/"),
            new KeyValuePair("TransactionLogging:Version", "1"),
            new KeyValuePair("TransactionLogging:Queue:Enabled", "True")
        };
    
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.AddInMemoryCollection(confValues);
    
        var confRoot = builder.Build();
        StartupExtensions.YourExtensionMethod(mvcBuilder); // Any other params
    }
    

提交回复
热议问题