ivaylokenov / MyTested.AspNetCore.Mvc

Fluent testing library for ASP.NET Core MVC.
https://docs.mytestedasp.net/
Other
1.73k stars 175 forks source link

I am not using a Startup.cs in my WebAPI #408

Closed sonicmouse closed 1 year ago

sonicmouse commented 1 year ago

In your example, you do this:

public class TestStartup : Startup
{
    public void ConfigureTestServices(IServiceCollection services)
    {
        base.ConfigureServices(services);

        // Replace only your own custom services. The ASP.NET Core ones 
        // are already replaced by MyTested.AspNetCore.Mvc. 
        services.Replace<IService, MockedService>();
    }
}

By my project doesn't have a Startup class. How do I use this framework? I can't find anything about it online and there are no examples on how to use your framework with the new .NET6 WebAPI format where the Startup file is omitted and the entire pipeline is built in Program.cs

stefanMinch3v commented 1 year ago

Hey sonicmouse, you can create a partial Program class and inherit from it also in case you need IConfiguration or IWebHostEnvironment for replacing something on your mock services you can inject them in the constructor. Example: just place it in the same Program.cs file at the bottom of it public partial class Program { public Program(IConfiguration configuration, IWebHostEnvironment environment) { this.MyConfiguration = configuration; this.MyWebHostEnvironment = environment; }

public IConfiguration MyConfiguration { get; }
public IWebHostEnvironment MyWebHostEnvironment { get; }

} // the usual TestStartup file but this time inherits from the partial Program class public class TestStartup : Program { public TestStartup(IConfiguration configuration, IWebHostEnvironment hostEnvironment) : base(configuration, hostEnvironment) { }

public void ConfigureTestServices(IServiceCollection services)
{
    services
        .AddApplication(base.MyConfiguration)
        .AddInfrastructure(base.MyConfiguration, base.MyWebHostEnvironment, false)
        .AddWebComponents();

    services.ReplaceSingleton<IEmailSender, EmailSenderMock>();
    services.ReplaceScoped<UserManager<User>, UserManagerMock>();
}

}

This is what works for me :)

sonicmouse commented 1 year ago

Excellent -- Thank you!