Tôi có một ứng dụng cốt lõi asp.net sử dụng dependency injection định nghĩa trong lớp startup.cs của ứng dụng:làm thế nào để đơn vị kiểm tra asp.net ứng dụng cốt lõi với dependency injection constructor
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>();
Điều này cho phép một cái gì đó như này:
[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;
}
Điều này rất gọn gàng. Nhưng trở thành một vấn đề khi tôi muốn kiểm tra đơn vị. Bởi vì thư viện thử nghiệm của tôi không có startup.cs nơi tôi thiết lập tiêm phụ thuộc. Vì vậy, một lớp với các giao diện này như các tham số sẽ chỉ là null.
namespace TestLibrary
{
public class FootballAPIService
{
private readonly IMatchRepository _matchRepository;
private readonly ITeamRepository _teamRepository;
public FootballAPIService(IMatchRepository matchRepository, ITeamRepository teamRepository)
{
_matchRepository = matchRepository;
_teamRepository = teamRepository;
Trong đoạn mã trên, trong thư viện kiểm tra, _matchRepository và _teamRepository, chỉ sẽ rỗng. :(
Tôi có thể làm điều gì đó như ConfigureServices, nơi tôi xác định dependency injection trong dự án thư viện thử nghiệm của tôi?
Là một phần của thử nghiệm của bạn, bạn nên thiết lập sự phụ thuộc đối với hệ thống của bạn Dưới Test (SUT). Thông thường bạn làm điều này bằng cách tạo ra mô hình của các phụ thuộc trước khi tạo SUT. Nhưng để tạo SUT, chỉ cần gọi 'SUT mới (mockDependency);' là tốt cho thử nghiệm của bạn. –