Browse Source

Add a no-op IServerAddressesFeature implementation to TestServer.Features (#41570)

Philipp Voronin 3 years ago
parent
commit
f73127373a

+ 11 - 3
src/Hosting/TestHost/src/TestServer.cs

@@ -4,6 +4,7 @@
 using System.Net.Http;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Hosting.Server;
+using Microsoft.AspNetCore.Hosting.Server.Features;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Http.Features;
 using Microsoft.Extensions.Options;
@@ -19,13 +20,20 @@ public class TestServer : IServer
     private bool _disposed;
     private ApplicationWrapper? _application;
 
+    private static FeatureCollection CreateTestFeatureCollection()
+    {
+        var features = new FeatureCollection();
+        features.Set<IServerAddressesFeature>(new ServerAddressesFeature());
+        return features;
+    }
+
     /// <summary>
     /// For use with IHostBuilder.
     /// </summary>
     /// <param name="services"></param>
     /// <param name="optionsAccessor"></param>
     public TestServer(IServiceProvider services, IOptions<TestServerOptions> optionsAccessor)
-        : this(services, new FeatureCollection(), optionsAccessor)
+        : this(services, CreateTestFeatureCollection(), optionsAccessor)
     {
     }
 
@@ -50,7 +58,7 @@ public class TestServer : IServer
     /// </summary>
     /// <param name="services"></param>
     public TestServer(IServiceProvider services)
-        : this(services, new FeatureCollection())
+        : this(services, CreateTestFeatureCollection())
     {
     }
 
@@ -71,7 +79,7 @@ public class TestServer : IServer
     /// </summary>
     /// <param name="builder"></param>
     public TestServer(IWebHostBuilder builder)
-        : this(builder, new FeatureCollection())
+        : this(builder, CreateTestFeatureCollection())
     {
     }
 

+ 18 - 0
src/Hosting/TestHost/test/TestServerTests.cs

@@ -279,6 +279,24 @@ public class TestServerTests
         // Is inside configure callback
     }
 
+    [Fact]
+    public void TestServerConstructedWithoutFeatureCollectionHasServerAddressesFeature()
+    {
+        // Arrange
+        var builder = new WebHostBuilder()
+            .Configure(applicationBuilder =>
+            {
+                var serverAddressesFeature = applicationBuilder.ServerFeatures.Get<IServerAddressesFeature>();
+                Assert.NotNull(serverAddressesFeature);
+            });
+
+        // Act
+        new TestServer(builder);
+
+        // Assert
+        // Is inside configure callback
+    }
+
     [Fact]
     public void TestServerConstructorWithNullFeatureCollectionThrows()
     {

+ 3 - 0
src/Mvc/test/WebSites/SimpleWebSiteWithWebApplicationBuilder/Program.cs

@@ -11,6 +11,9 @@ builder.Services.AddControllers();
 
 var app = builder.Build();
 
+// just to make sure that it does not cause exceptions
+app.Urls.Add("http://localhost:8080");
+
 app.MapControllers();
 
 app.MapGet("/", () => "Hello World");