比如要对这样一个类进行单元测试:
public class UCenterService { private IMemcachedClient _memcachedClient; private ILogger<UserService> _logger; public UCenterService( IMemcachedClient memcachedClient, ILogger<UCenterService> logger) { _memcachedClient = memcachedClient; _logger = logger; } //... }
如何在单元测试中通过依赖注入创建这个类的实例?
目前的临时解决方法:
public class UCenterServiceTest { private UCenterService _ucenterService; public UCenterServiceTest() { IServiceCollection services = new ServiceCollection(); services.AddLogging(); services.AddSingleton<IMemcachedClient, NullMemcachedClient>(); services.AddScoped<UCenterService>(); IServiceProvider serviceProvider = services.BuildServiceProvider(); var memcacheClient = serviceProvider.GetService<IMemcachedClient>(); _ucenterService = serviceProvider.GetService<UCenterService>(); } [Fact] public void IntanceIsNotNull() { Assert.NotNull(_ucenterService); } }
更理想的解决方法:单元测试的类也能通过构造函数依赖注入