首页 新闻 会员 周边 捐助

.net core的xunit单元测试中如何使用依赖注入

0
悬赏园豆:30 [已解决问题] 解决于 2017-02-18 20:38

比如要对这样一个类进行单元测试:

复制代码
public class UCenterService
{
    private IMemcachedClient _memcachedClient;
    private ILogger<UserService> _logger;

    public UCenterService(
        IMemcachedClient memcachedClient,
        ILogger<UCenterService> logger)
    {
        _memcachedClient = memcachedClient;
        _logger = logger;
    }

    //...
}
复制代码

如何在单元测试中通过依赖注入创建这个类的实例?

dudu的主页 dudu | 高人七级 | 园豆:30778
提问于:2016-12-21 10:43
< >
分享
最佳答案
0

目前的临时解决方法:

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);
    }
}

更理想的解决方法:单元测试的类也能通过构造函数依赖注入

dudu | 高人七级 |园豆:30778 | 2016-12-21 14:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册