0 Comments

 

When you have an ASP .NET Core MVC api controller and you want to quickly debug the controller endpoint, you can use the code below.

Just make sure, you set the “Copy to Output Directory” to “Copy always” or “Copy if newer” on the appsettings.json file, inside the unit test project.

 

Code

 

using System;

using System.Net.Http;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.TestHost;

using Microsoft.Extensions.Configuration;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using XmlInterface.WebApi;

 

namespace UnitTest

{

    [TestClass]

    public class SpikeUnitTest

    {

        /// <summary>

        /// https://geeklearning.io/a-different-approach-to-test-your-asp-net-core-application/

        /// </summary>

        [TestMethod]

        public async Task Run()

        {

            IConfigurationRoot configuration = new ConfigurationBuilder()

            .SetBasePath(AppContext.BaseDirectory)

            .AddJsonFile(“appsettings.json”)

            .Build();

 

            // UseConfiguration

            var webHostBuilder = new WebHostBuilder();

            webHostBuilder

                .UseConfiguration(configuration)

                .UseStartup<Startup>();

 

            var testServer = new TestServer(webHostBuilder);

            HttpClient httpClient = testServer.CreateClient();

            var response = await httpClient.GetAsync(“/api/Test”);

 

            Assert.IsTrue(true);

        }

    }

}

<

p style=”background: #1e1e1e”>
 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts