How to unit test your program.cs file

Zephyr Hawthorne
2 min readMar 16, 2023

--

Here’s an example unit test for the program.cs file using Xunit and Moq:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;
using Moq;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace WebApplication2.Tests
{
public class ProgramTests
{
[Fact]
public async Task Main_ShouldRunApplication()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureAppConfiguration((context, config) =>
{
// Add configuration settings here if necessary
})
.ConfigureServices(services =>
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Mock.Of<IConfigurationSection>())
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
services.AddControllers();
services.AddSwaggerGen();
})
.Configure(app =>
{
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapSwagger();
});
});
using var server = new TestServer(builder);
using var client = server.CreateClient();
// Act
var response = await client.GetAsync("/");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
}

Microsoft.AspNetCore.TestHost is a testing library that allows you to create an in-memory test server for your ASP.NET Core application. It's part of the Microsoft.AspNetCore.Testing package and is included by default in new ASP.NET Core projects created using the dotnet new command.

The TestServer class in Microsoft.AspNetCore.TestHost creates an in-memory test server that can handle HTTP requests and responses. You can use this test server to write integration tests for your application without needing to deploy it to a real server.

Note that in this example, we’re testing that the server responds with a 404 Not Found status code when we make a GET request to the root URL (“/”). This is just a simple example of a unit test, and you should modify it to test the specific behavior of your application. You may also need to add additional services or configuration settings to the ConfigureServices method depending on your application's requirements.

--

--

No responses yet