Reputation: 11
I wrote a simple token generating API with ASP.NET Core 6. I need to do an integration test. When I write the integration test, it needs to reference the Program class, but I get an error
The ‘Program’ element is inaccessible due to the protection level
So after adding namespace and public, I get an error
CS0017: More than one entry point is defined in the program. Specify /main to specify the type containing the entry point.
I cannot solve it.
This is my Program.cs
:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using TokenProject.Model;
var builder = WebApplication.CreateBuilder(args);
// CORS yapılandırması
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAngularApp",
builder =>
{
builder.WithOrigins("http://localhost:4200") // Angular uygulamasının adresi
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials(); // Credentials ekledim
});
});
// JWT kimlik doğrulama yapılandırması
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine("Token validation failed: " + context.Exception.Message);
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine("Token validated: " + context.SecurityToken);
return Task.CompletedTask;
}
};
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
builder.Services.AddDbContext<TokenDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("TokenDB")));
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// CORS politikasını kullan
app.UseCors("AllowAngularApp");
// Authentication ve Authorization'ı kullan
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
TokenControllerTests
:
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using Newtonsoft.Json;
using Xunit;
namespace Token.IntegrationTests
{
public class TokenControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public TokenControllerTests(WebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task Get_Token_Endpoint_Returns_Success()
{
var request = new HttpRequestMessage(HttpMethod.Get, "/api/token");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
[Fact]
public async Task Post_Token_Returns_Success()
{
var tokenRequest = new
{
Username = "testuser",
Password = "P@ssw0rd"
};
var content = new StringContent(JsonConvert.SerializeObject(tokenRequest), Encoding.UTF8, "application/json");
var response = await _client.PostAsync("http://localhost:7125/api/Auth/login", content);
response.EnsureSuccessStatusCode();
}
}
}
Upvotes: 0
Views: 41
Reputation: 36655
Add the following code to the end of your Program.cs
( that is to say add the code after app.Run();
):
app.Run();
public partial class Program { }
Upvotes: 0