Ho un'applicazione principale asp.net che utilizza iniezione di dipendenza definito nella classe startup.cs dell'applicazione:come unità di applicazione provino asp.net con iniezione costruttore dipendenza
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>();
Questo permette simile this:
[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;
}
Questo è molto pulito. Ma diventa un problema quando voglio un test unitario. Perché la mia libreria di test non ha un startup.cs in cui ho impostato l'iniezione delle dipendenze. Quindi una classe con queste interfacce come parametri sarà null.
namespace TestLibrary
{
public class FootballAPIService
{
private readonly IMatchRepository _matchRepository;
private readonly ITeamRepository _teamRepository;
public FootballAPIService(IMatchRepository matchRepository, ITeamRepository teamRepository)
{
_matchRepository = matchRepository;
_teamRepository = teamRepository;
Nel codice precedente, nella libreria di test, _matchRepository e _teamRepository, sarà solo nullo. :(
Posso fare qualcosa di simile ConfigureServices, dove io definisco l'iniezione di dipendenza nel mio progetto libreria di test?
Come parte del test è necessario impostare le dipendenze per il sistema in prova (SUT). Solitamente lo fai creando delle finte dipendenze prima di creare il SUT. Ma per creare il SUT è sufficiente chiamare 'new SUT (mockDependency);' va bene per il test. Pacchetto –