How to Unit Test Startup.cs in .NET Core

前端 未结 3 1916
一向
一向 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 02:04

    I also had a similar problem, but managed to get around that by using the WebHost in AspNetCore and essentially re-creating what program.cs does, and then Asserting that all of my services exist and are not null. You could go a step further and execute specific extensions for IServices with .ConfigureServices or actually perform operations with the services you created to make sure they were constructed properly.

    One key, is I created a unit test startup class that inherits from the startup class I'm testing so that I don't have to worry about separate assemblies. You could use composition if you prefer to not use inheritance.

    [TestClass]
    public class StartupTests
    {
        [TestMethod]
        public void StartupTest()
        {
            var webHost = Microsoft.AspNetCore.WebHost.CreateDefaultBuilder().UseStartup().Build();
            Assert.IsNotNull(webHost);
            Assert.IsNotNull(webHost.Services.GetRequiredService());
            Assert.IsNotNull(webHost.Services.GetRequiredService());
        }
    }
    
    public class Startup : MyStartup
    {
        public Startup(IConfiguration config) : base(config) { }
    }
    

提交回复
热议问题