在单元测试中使用依赖注入 class

Using dependency injection in a unit test class

我正在使用 xunit 为我的网站编写单元测试 api。我的网站 api 使用依赖注入来传递 DbContext 和 IConfiguration 作为使用构造函数注入的参数。我希望能够在我的单元测试项目中执行此操作,以便我可以轻松访问 DbContext 和 IConfiguration。我读过有关使用夹具来执行此操作的信息,但我还没有找到一个很好的例子来说明如何处理。我看过使用 TestServer class 的文章,但我的项目针对 .NETCoreApp1.1 框架,它不允许我使用 TestServer class。这里有什么建议吗?

您确定需要在测试中使用这些依赖项吗? 根据单元测试理念,考虑使用一些模拟框架来为 DbContext 和 IConfiguration 的虚拟实例提供合适的行为和值。 尝试查看 NSubstitute 或 Moq 框架。

我发现创建 'fake' 配置以传递到需要 IConfiguration 实例的方法的最简单方法如下:

[TestFixture]
public class TokenServiceTests
{
    private readonly IConfiguration _configuration;

    public TokenServiceTests()
    {
        var settings = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("JWT:Issuer", "TestIssuer"),
            new KeyValuePair<string, string>("JWT:Audience", "TestAudience"),
            new KeyValuePair<string, string>("JWT:SecurityKey", "TestSecurityKey")
        };
        var builder = new ConfigurationBuilder().AddInMemoryCollection(settings);
        this._configuration = builder.Build();
    }

    [Test(Description = "Tests that when [GenerateToken] is called with a null Token Service, an ArgumentNullException is thrown")]
    public void When_GenerateToken_With_Null_TokenService_Should_Throw_ArgumentNullException()
    {
        var service = new TokenService(_configuration);
        Assert.Throws<ArgumentNullException>(() => service.GenerateToken(null, new List<Claim>()));
    }
}

[这显然是使用 NUnit 作为测试框架]