Wie teste ich die asp.net-Kernanwendung mit Konstruktorabhängigkeitsinjektion?

Ich habe eine asp.net-Kernanwendung, die die Abhängigkeitsinjektion verwendet, die in der startup.cs-Klasse der Anwendung definiert ist:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration["Data:FotballConnection:DefaultConnection"]));


        // Repositories
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddScoped<IUserRoleRepository, UserRoleRepository>();
        services.AddScoped<IRoleRepository, RoleRepository>();
        services.AddScoped<ILoggingRepository, LoggingRepository>();

        // Services
        services.AddScoped<IMembershipService, MembershipService>();
        services.AddScoped<IEncryptionService, EncryptionService>();

        // new repos
        services.AddScoped<IMatchService, MatchService>();
        services.AddScoped<IMatchRepository, MatchRepository>();
        services.AddScoped<IMatchBetRepository, MatchBetRepository>();
        services.AddScoped<ITeamRepository, TeamRepository>();

        services.AddScoped<IFootballAPI, FootballAPIService>();

Dies erlaubt so etwas:

[Route("api/[controller]")]
public class MatchController : AuthorizedController
{
    private readonly IMatchService _matchService;
    private readonly IMatchRepository _matchRepository;
    private readonly IMatchBetRepository _matchBetRepository;
    private readonly IUserRepository _userRepository;
    private readonly ILoggingRepository _loggingRepository;

    public MatchController(IMatchService matchService, IMatchRepository matchRepository, IMatchBetRepository matchBetRepository, ILoggingRepository loggingRepository, IUserRepository userRepository)
    {
        _matchService = matchService;
        _matchRepository = matchRepository;
        _matchBetRepository = matchBetRepository;
        _userRepository = userRepository;
        _loggingRepository = loggingRepository;
    }

Das ist sehr ordentlich. Wird aber zum Problem wenn ich Unit Test machen will. Weil meine Testbibliothek kein startup.cs hat, in dem ich die Abhängigkeitsinjektion einrichte. Eine Klasse mit diesen Schnittstellen als Parameter ist also einfach null.

namespace TestLibrary
{
    public class FootballAPIService
    {
        private readonly IMatchRepository _matchRepository;
        private readonly ITeamRepository _teamRepository;

        public FootballAPIService(IMatchRepository matchRepository, ITeamRepository teamRepository)

        {
            _matchRepository = matchRepository;
            _teamRepository = teamRepository;

Im obigen Code in der Testbibliothek, _matchRepository und _teamRepository, wird nur @ seNul. :

Kann ich so etwas wie ConfigureServices ausführen, bei dem ich die Abhängigkeitsinjektion in meinem Testbibliotheksprojekt definiere?

Antworten auf die Frage(8)

Ihre Antwort auf die Frage