Xunit Testing EFcore Repositories InMemory DB - c#

I am trying to unit test the repositories, I am using InMemory option in EFCore . This is the method
[Fact]
public async Task GetCartsAsync_Returns_CartDetail()
{
ICartRepository sut = GetInMemoryCartRepository();
CartDetail cartdetail = new CartDetail()
{
CommercialServiceName = "AAA"
};
bool saved = await sut.SaveCartDetail(cartdetail);
//Assert
Assert.True(saved);
//Assert.Equal("AAA", CartDetail[0].CommercialServiceName);
//Assert.Equal("BBB", CartDetail[1].CommercialServiceName);
//Assert.Equal("ZZZ", CartDetail[2].CommercialServiceName);
}
private ICartRepository GetInMemoryCartRepository()
{
DbContextOptions<SostContext> options;
var builder = new DbContextOptionsBuilder<SostContext>();
builder.UseInMemoryDatabase($"database{Guid.NewGuid()}");
options = builder.Options;
SostContext personDataContext = new SostContext(options);
personDataContext.Database.EnsureDeleted();
personDataContext.Database.EnsureCreated();
return new CartRepository(personDataContext);
}
I am getting error which say
System.TypeLoadException : Method 'ApplyServices' in type
'Microsoft.EntityFrameworkCore.Infrastructure.Internal.InMemoryOptionsExtension' from assembly
'Microsoft.EntityFrameworkCore.InMemory, Version=1.0.1.0, Culture=neutral,
PublicKeyToken=adb9793829ddae60' does not have an implementation.
Microsoft.
EntityFrameworkCore.InMemoryDbContextOptionsExtensions.UseInMemoryDatabase(DbContextOptionsBuilder
optionsBuilder, String databaseName, Action`1 inMemoryOptionsAction)
Microsoft.EntityFrameworkCore.InMemoryDbContextOptionsExtensions.UseInMemoryDatabase[TContext]
(DbContextOptionsBuilder`1 optionsBuilder, String databaseName, Action`1 inMemoryOptionsAction)
My reference is from https://www.carlrippon.com/testing-ef-core-repositories-with-xunit-and-an-in-memory-db/
Please suggest me where i am going wrong with the current implementation . Thanks in Advance

I suggest reading the official Microsoft documentation about integration testing.
https://learn.microsoft.com/fr-fr/aspnet/core/test/integration-tests?view=aspnetcore-3.0
Secondly, I you start adding this kind of boilerplate to create your tests with the memory database you will stop doing it very soon.
For integration tests, you should be near to your development configuration.
Here my configuration files and a usage in my CustomerController :
Integration Startup File
Have all think about database creation and dependency injection
public class IntegrationStartup : Startup
{
public IntegrationStartup(IConfiguration configuration) : base(configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public override void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();
services.AddDbContext<StreetJobContext>(options =>
{
options.UseInMemoryDatabase("InMemoryAppDb");
});
//services.InjectServices();
//here you can set your ICartRepository DI configuration
services.AddMvc(option => option.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddApplicationPart(Assembly.Load(new AssemblyName("StreetJob.WebApp")));
ConfigureAuthentication(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using (var serviceScope = serviceScopeFactory.CreateScope())
{
//Here you can add some data configuration
}
app.UseMvc();
}
The fake startup
it's quite similar to the one in the Microsoft documentation
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override IWebHostBuilder CreateWebHostBuilder()
{
return WebHost.CreateDefaultBuilder(null)
.UseStartup<TStartup>();
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseSolutionRelativeContentRoot(Directory.GetCurrentDirectory());
builder.ConfigureAppConfiguration(config =>
{
config.AddConfiguration(new ConfigurationBuilder()
//custom setting file in the test project
.AddJsonFile($"integrationsettings.json")
.Build());
});
builder.ConfigureServices(services =>
{
});
}
}
The controller
public class CustomerControllerTest : IClassFixture<CustomWebApplicationFactory<IntegrationStartup>>
{
private readonly HttpClient _client;
private readonly CustomWebApplicationFactory<IntegrationStartup> _factory;
private readonly CustomerControllerInitialization _customerControllerInitialization;
public CustomerControllerTest(CustomWebApplicationFactory<IntegrationStartup> factory)
{
_factory = factory;
_client = _factory.CreateClient();
}
}
With this kind of setting, testing the integration tests are very similar to the development controller.
It's a quite good configuration for TDD Developers.

Related

ConfigurationProvider with other dependencies

I've implemented my customs IConfigurationProvider and IConfigurationSource.
public class MyConfigurationSource : IConfigurationSource
{
public string Foo { get; set; }
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new MyConfigurationProvider(this);
}
}
internal class MyConfigurationProvider : ConfigurationProvider
{
public MyConfigurationSource Source { get; };
public MyConfigurationProvider()
{
Source = source
}
public override void Load()
{
// I'd like to assign here my configuration data by using some dependencies
Data = ....
}
}
I do the build of my Configuration in the Startup constructor (I override the configuration created by CreateDefaultBuilder):
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddMyConfiguration("myfoovalue")
.Build();
Extension method:
public static IConfigurationBuilder AddMyConfiguration(this IConfigurationBuilder builder, string foo)
{
return builder.Add(new MyConfigurationSource
{
Foo = url
});
}
I wish I could somehow inject services to be used in Load method. The problem here is that the configuration build is done in the Startup constructor. I can only inject dependencies that I have available in this constructor: IWebHostEnvironment, IHostEnvironment, IConfiguration and all I added when I built the WebHost. Also these dependencies would have to be passed the moment I call the AddMyConfiguration extension method. How could I use dependencies that don't even exist at that moment?
A bit late answer.
It's obvious there's no way to use the container, that was built using Startup.ConfigureServices, in the MyConfigurationSource/MyConfigurationProvider simply because by the time ConfigurationBuilder.Build is invoked, ServiceCollection.BuildServiceProvider has not been invoked.
A typical workaround would be to create another instance of IServiceProvider with required configuration and use it inside MyConfiguration....
Something like
internal class MyConfigurationProvider : ConfigurationProvider
{
public MyConfigurationSource Source { get; };
public MyConfigurationProvider()
{
Source = source;
ServiceProvider = BuildServiceProvider();
}
public override void Load()
{
// I'd like to assign here my configuration data by using some dependencies
Data = ServiceProvider.GetRequiredService<IMyService>().GetData();
}
protected virtual void ConfigureServices(IServiceCollection services)
{
services.AddMyService();
// etc.
}
private IServiceProvider BuildServiceProvider()
{
var services = new ServiceCollection();
ConfigureServices(services);
return services.BuildServiceProvider();
}
}
but this might not always be appropriate so I would also consider setting the value directly (though I didn't find any official information about how good this approach is)
public class Startup
{
public void Configure(IApplicationBuilder app)
{
...
app.SetupMyConfiguration();
...
}
}
...
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder SetupMyConfiguration(this IApplicationBuilder app)
{
var configuration = app
.ApplicationServices
.GetRequiredService<IConfiguration>(); // alternatively IOptions<MyOptions>
var myService = app
.ApplicationServices
.GetRequiredService<IMyService>();
configuration["MyKey"] = myService.GetData("MyKey");
}
}
UPD.
There's also an alternative with using strongly typed options object and IConfigureOptions.
public class MyConfigurationBuilder : IConfigureOptions<MyConfiguration>
{
private readonly IConfiguration _configuration;
private readonly IMyService _service;
public MyConfigurationBuilder(
IConfiguration configuration,
IMyService service)
{
_configuration = configuration;
_service = service;
}
public void Configure(MyConfiguration myConfiguration)
{
// you may set static configuration values
_configuration
.GetSection(nameof(MyConfiguration))
.Bind(myConfiguration);
// or from DI
myConfiguration.Data = _service.GetData();
// here we still can update IConfiguration,
// though it doesn't seem to be a good idea
_configuration["MyKey"] = _service.GetData("MyKey");
}
}
services.AddSingleton<IConfigureOptions<MyConfiguration>, MyConfigurationBuilder>();
or inject dependencies directly into MyConfiguration
services.Configure<MyConfiguration>(
serviceProvider =>
ActivatorUtilities.CreateInstance<MyConfiguration>(serviceProvider, "staticConfigValue"));
public class MyConfiguration
{
public MyConfiguration(string staticValue, IMyService service)
{
...
}
}
public class Service
{
public Service(IOptions<MyConfiguration> options) {}
}

Singleton service and EF Core dbContext

The application uses ASP.NET Core 3. At the first call, a project class service is created.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
string connection = Configuration.GetConnectionString("ConnectionDB");
services.AddDbContext<DataBaseContext>(options => options.UseSqlServer(connection), ServiceLifetime.Transient, ServiceLifetime.Singleton);
services.AddSingleton<Project>();
}
Project.cs
public class Project
{
private readonly DataBaseContext _dbContext;
public Project(DataBaseContext dbContext)
{
_dbContext = dbContext;
Init();
}
public async void Init()
{
await SomeMethod('text');
}
public async Task SomeMethod(string message)
{
_dbContext.Items.Add(message);
await _dbContext.SaveChangesAsync();
}
}
This is not entirely correct and I want to create a service when the application starts.
public void ConfigureServices(IServiceCollection services)
{
// AddDbContext
Project project = new Project(dbContext); // How to get dbcontext?
services.AddSingleton(typeof(Project), project);
}
How to pass dbcontext in this case?
UPDATE
Now in the Stratup class, I call the init () method of the project service.
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
Project project = serviceProvider.GetService<Project>();
project.Init();
// some code
}
Dunno why would you not use the automatic Dependecy Injection at your first code
Singleton are created upon app start. And as long as the init method is called inside the constructor it will run. So this code will work on your case already
public void ConfigureServices(IServiceCollection services)
{
string connection = Configuration.GetConnectionString("ConnectionDB");
services.AddDbContext<DataBaseContext>(options => options.UseSqlServer(connection), ServiceLifetime.Transient, ServiceLifetime.Singleton);
services.AddSingleton<Project>();
}
But anyway if you insist on instantiating the Project class then you can use this. Get the DBContext using ServiceProvider.
public void ConfigureServices(IServiceCollection services)
{
// AddDbContext
var sp = services.BuildServiceProvider();
var dbContext = sp.GetRequiredService<DbContext>();
Project project = new Project(dbContext);
services.AddSingleton(typeof(Project), project);
}

Using ASP.NET DI for SignalR with TinyIoC

In a project, I'm using Nancy/TinyIoC for Dependency Injection. I had no problems thus far.
I added SignalR to my project and setup my hubs so that I'm injecting IHubContext into my hub.
I'm running into a problem that when TinyIoC tries to resolve one of its dependency trees, it runs into an ASP.NET type and cannot resolve such. How do I work around this? My first guess was to register the type within TinyIoC, but that seems tedious.
Here's what I have:
public class Startup
{
public void Configure(IApplicationBuilder builder)
{
// Register types from ASP.net
// Pass instances to UseNancy
var hubContext = builder.ApplicationServices.GetService<IHubContext<MessageSender>>();
builder
.UseCors(AllowAllOrigins)
.UseSignalR(HubRegistration.RouteRegistrations)
.UseOwin(x => x.UseNancy());
}
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(AllowAllOrigins,
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddSignalR();
}
}
public class MessageRepo : IRepository<Message>
{
private readonly IDatabase<Message> _database;
private readonly IValidator<Message> _messageValidator;
private readonly IMessageSender<Message> _hubContext;
public MessageRepo(IDatabase<Message> database, IValidator<Message> messageValidator, IMessageSender<Message> hubContext)
{
_database = database;
_messageValidator = messageValidator;
_hubContext = hubContext;
}
}
public class MessageSender : Hub, IMessageSender<Message>
{
public MessageSender(IHubContext<MessageSender> context)
{
_context = context;
}
}

Net Core: Execute All Dependency Injection in Xunit Test for AppService, Repository, etc

I am trying to implement Dependency Injection in Xunit test for AppService. Ideal goal is to run the original application program Startup/configuration, and use any dependency injection that was in Startup, instead of reinitializing all the DI again in my test, thats the whole Goal in question.
Update: Mohsen's answer is close. Need to update couple syntax/requirement errors to work.
For some reason, original application works and can call Department App Service. However, it cannot call in Xunit. Finally got Testserver working using Startup and Configuration from original application.
Now receiving error below:
Message: The following constructor parameters did not have matching fixture data: IDepartmentAppService departmentAppService
namespace Testing.IntegrationTests
{
public class DepartmentAppServiceTest
{
public DBContext context;
public IDepartmentAppService departmentAppService;
public DepartmentAppServiceTest(IDepartmentAppService departmentAppService)
{
this.departmentAppService = departmentAppService;
}
[Fact]
public async Task Get_DepartmentById_Are_Equal()
{
var options = new DbContextOptionsBuilder<SharedServicesContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.Options;
context = new DBContext(options);
TestServer _server = new TestServer(new WebHostBuilder()
.UseContentRoot("C:\\OriginalApplication")
.UseEnvironment("Development")
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath("C:\\OriginalApplication")
.AddJsonFile("appsettings.json")
.Build()).UseStartup<Startup>());
context.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName = "ABC" });
context.SaveChanges();
var departmentDto = await departmentAppService.GetDepartmentById(2);
Assert.Equal("123", departmentDto.DepartmentCode);
}
}
}
I am receiving this error:
Message: The following constructor parameters did not have matching fixture data: IDepartmentAppService departmentAppService
Need to use Dependency injection in testing just like real application.
Original application does this. Answers below are not currently sufficient , one uses mocking which is not current goal, other answer uses Controller which bypass question purpose.
Note: IDepartmentAppService has dependency on IDepartmentRepository which is also injected in Startup class, and Automapper dependencies. This is why calling the whole startup class.
Good Resources:
how to unit test asp.net core application with constructor dependency injection
Dependency injection in Xunit project
You are mixing unit test with integration test. TestServer is for integration test and if you want to reuse Startup class to avoid register dependencies again, you should use HttpClient and make HTTP call to controller and action that use IDepartmentAppService.
If you want do unit test, you need to setup DI and register all needed dependencies to test IDepartmentAppService.
Using DI through Test Fixture:
public class DependencySetupFixture
{
public DependencySetupFixture()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddDbContext<SharedServicesContext>(options => options.UseInMemoryDatabase(databaseName: "TestDatabase"));
serviceCollection.AddTransient<IDepartmentRepository, DepartmentRepository>();
serviceCollection.AddTransient<IDepartmentAppService, DepartmentAppService>();
ServiceProvider = serviceCollection.BuildServiceProvider();
}
public ServiceProvider ServiceProvider { get; private set; }
}
public class DepartmentAppServiceTest : IClassFixture<DependencySetupFixture>
{
private ServiceProvider _serviceProvide;
public DepartmentAppServiceTest(DependencySetupFixture fixture)
{
_serviceProvide = fixture.ServiceProvider;
}
[Fact]
public async Task Get_DepartmentById_Are_Equal()
{
using(var scope = _serviceProvider.CreateScope())
{
// Arrange
var context = scope.ServiceProvider.GetServices<SharedServicesContext>();
context.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName = "ABC" });
context.SaveChanges();
var departmentAppService = scope.ServiceProvider.GetServices<IDepartmentAppService>();
// Act
var departmentDto = await departmentAppService.GetDepartmentById(2);
// Arrange
Assert.Equal("123", departmentDto.DepartmentCode);
}
}
}
Using dependency injection with unit test is not good idea and you should avoid that. by the way if you want don't repeat your self for registering dependencies, you can wrap your DI configuration in another class and use that class anywhere you want.
Using DI through Startup.cs:
public class IocConfig
{
public static IServiceCollection Configure(IServiceCollection services, IConfiguration configuration)
{
serviceCollection
.AddDbContext<SomeContext>(options => options.UseSqlServer(configuration["ConnectionString"]));
serviceCollection.AddScoped<IDepartmentRepository, DepartmentRepository>();
serviceCollection.AddScoped<IDepartmentAppService, DepartmentAppService>();
.
.
.
return services;
}
}
in Startup class and ConfigureServices method just useIocConfig class:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
IocConfig.Configure(services, configuration);
services.AddMvc();
.
.
.
if you don't want use IocConfig class, change ConfigureServices in Startup class:
public IServiceCollection ConfigureServices(IServiceCollection services)
{
.
.
.
return services;
and in test project reuse IocConfig or Startup class:
public class DependencySetupFixture
{
public DependencySetupFixture()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true));
configuration = builder.Build();
var services = new ServiceCollection();
// services = IocConfig.Configure(services, configuration)
// or
// services = new Startup(configuration).ConfigureServices(services);
ServiceProvider = services.BuildServiceProvider();
}
public ServiceProvider ServiceProvider { get; private set; }
}
and in test method:
[Fact]
public async Task Get_DepartmentById_Are_Equal()
{
using (var scope = _serviceProvider.CreateScope())
{
// Arrange
var departmentAppService = scope.ServiceProvider.GetServices<IDepartmentAppService>();
// Act
var departmentDto = await departmentAppService.GetDepartmentById(2);
// Arrange
Assert.Equal("123", departmentDto.DepartmentCode);
}
}
Use Custom Web Application Factory and ServiceProvider.GetRequiredService below, feel free to edit and optimize the answer
CustomWebApplicationFactory:
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
{
var type = typeof(TStartup);
var path = #"C:\\OriginalApplication";
configurationBuilder.AddJsonFile($"{path}\\appsettings.json", optional: true, reloadOnChange: true);
configurationBuilder.AddEnvironmentVariables();
});
// if you want to override Physical database with in-memory database
builder.ConfigureServices(services =>
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
services.AddDbContext<ApplicationDBContext>(options =>
{
options.UseInMemoryDatabase("DBInMemoryTest");
options.UseInternalServiceProvider(serviceProvider);
});
});
}
}
Integration Test:
public class DepartmentAppServiceTest : IClassFixture<CustomWebApplicationFactory<OriginalApplication.Startup>>
{
public CustomWebApplicationFactory<OriginalApplication.Startup> _factory;
public DepartmentAppServiceTest(CustomWebApplicationFactory<OriginalApplication.Startup> factory)
{
_factory = factory;
_factory.CreateClient();
}
[Fact]
public async Task ValidateDepartmentAppService()
{
using (var scope = _factory.Server.Host.Services.CreateScope())
{
var departmentAppService = scope.ServiceProvider.GetRequiredService<IDepartmentAppService>();
var dbtest = scope.ServiceProvider.GetRequiredService<ApplicationDBContext>();
dbtest.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName = "ABC" });
dbtest.SaveChanges();
var departmentDto = await departmentAppService.GetDepartmentById(2);
Assert.Equal("123", departmentDto.DepartmentCode);
}
}
}
Resources:
https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2
https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api
When you are testing. You need to use mocking libraries or Inject your service directly on contructor ie.
public DBContext context;
public IDepartmentAppService departmentAppService;
/// Inject DepartmentAppService here
public DepartmentAppServiceTest(DepartmentAppService departmentAppService)
{
this.departmentAppService = departmentAppService;
}

Net Core Integration Test: Run Startup.cs and Configuration from other Program

We are creating an Integration Unit test (Xunit), which is calling the Real Application Startup.cs.
For some reason, Real project can read Configuration file/property correctly, however running it from the Integration test, it cannot read it. Its not placing anything into Configuration (conf) variable below. How would I resolve this?
The reason is its not picking up is its not reading the internal dependency injection new from Net Core 2.2 which reads Configuration file. Trying to use .CreateDefaultBuilder Now.
IntegrationTest1.cs
TestServer _server = new TestServer(new WebHostBuilder() .UseContentRoot("C:\\RealProject\\RealProject.WebAPI")
.UseEnvironment("Development")
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath("C:\\RealProject\\RealProject.WebAPI")
.AddJsonFile("appsettings.json")
.Build())
.UseStartup<Startup>()
.UseStartup<Startup>());
Real Project Startup.cs
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
Configuration = configuration;
HostingEnvironment = hostingEnvironment;
}
public IHostingEnvironment HostingEnvironment { get; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var conf = Configuration;
IConfiguration appConf = conf.GetSection("ConnectionStrings");
var connstring = appConf.GetValue<string>("DatabaseConnection");
services.AddDbContext<DbContext>(a => a.UseSqlServer(connstring));
Appsettings.Json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DatabaseConnection": "Data Source=.;Initial Catalog=ApplicationDatabase;Integrated Security=True"
}
}
What you want to do is create a Factory for your WebApplication which takes a Startup type. You can then use the IClassFixture interface to share the context of this factory with all of your tests in your test class.
How this looks in practice is:
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup> where TStartup : class
{
public CustomWebApplicationFactory() { }
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.ConfigureTestServices(
services =>
{
services.Configure(AzureADDefaults.OpenIdScheme, (System.Action<OpenIdConnectOptions>)(o =>
{
// CookieContainer doesn't allow cookies from other paths
o.CorrelationCookie.Path = "/";
o.NonceCookie.Path = "/";
}));
}
)
.UseEnvironment("Production")
.UseStartup<Startup>();
}
}
public class AuthenticationTests : IClassFixture<CustomWebApplicationFactory<Startup>>
{
private HttpClient _httpClient { get; }
public AuthenticationTests(CustomWebApplicationFactory<Startup> fixture)
{
WebApplicationFactoryClientOptions webAppFactoryClientOptions = new WebApplicationFactoryClientOptions
{
// Disallow redirect so that we can check the following: Status code is redirect and redirect url is login url
// As per https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#test-a-secure-endpoint
AllowAutoRedirect = false
};
_httpClient = fixture.CreateClient(webAppFactoryClientOptions);
}
[Theory]
[InlineData("/")]
[InlineData("/Index")]
[InlineData("/Error")]
public async Task Get_PagesNotRequiringAuthenticationWithoutAuthentication_ReturnsSuccessCode(string url)
{
// Act
HttpResponseMessage response = await _httpClient.GetAsync(url);
// Assert
response.EnsureSuccessStatusCode();
}
}
I followed the guide here to get this working in my own code.

Categories

Resources