简体   繁体   English

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

[英]Using dependency injection in a unit test class

I am using xunit to write unit tests for my web api. 我正在使用xunit为Web API编写单元测试。 My web api uses dependency injection to pass along a DbContext and an IConfiguration as parameters using constructor injection. 我的Web api使用构造函数注入将依赖项注入传递给DbContext和IConfiguration作为参数。 I would like to be able to do this in my unit tests project so that I can easily have access to the DbContext and IConfiguration. 我希望能够在我的单元测试项目中执行此操作,以便可以轻松访问DbContext和IConfiguration。 I have read about using a fixture to do this but I have not found a good example on how this would be handled. 我已经读过有关使用夹具来执行此操作的信息,但是我还没有找到有关如何处理它的好例子。 I have seen articles using the TestServer class but my project targets the .NETCoreApp1.1 framework which won't let me use the TestServer class. 我看过使用TestServer类的文章,但是我的项目针对的是.NETCoreApp1.1框架,该框架不允许我使用TestServer类。 Any suggestions here? 有什么建议吗?

Are you sure that you need to use those dependencies in your tests? 您确定需要在测试中使用那些依赖项吗? According to unit testing philosophy consider using some mock frameworks to provide dummy instances of your DbContext and IConfiguration with suitable behavior and values. 根据单元测试的原理,请考虑使用一些模拟框架为DbContext和IConfiguration的虚拟实例提供适当的行为和值。 Try to look into NSubstitute or Moq framework. 尝试研究NSubstitute或Moq框架。

The easiest way i've found to create a 'fake' configuration to pass into methods requiring an IConfiguration instance is like this: 我发现创建“假”配置以传递到需要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>()));
    }
}

[This obviously using NUnit as the testing framework] [这显然是使用NUnit作为测试框架]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM