【问题标题】:Using dependency injection in a unit test class在单元测试类中使用依赖注入
【发布时间】:2017-08-17 20:23:58
【问题描述】:
我正在使用 xunit 为我的 web api 编写单元测试。我的 web api 使用依赖注入来传递 DbContext 和 IConfiguration 作为使用构造函数注入的参数。我希望能够在我的单元测试项目中执行此操作,以便我可以轻松访问 DbContext 和 IConfiguration。我已经阅读了有关使用夹具来执行此操作的信息,但我还没有找到一个很好的例子来说明如何处理它。我看过使用TestServer 类的文章,但我的项目针对.NETCoreApp1.1 框架,它不允许我使用TestServer 类。这里有什么建议吗?
【问题讨论】:
标签:
c#
dependency-injection
xunit
【解决方案1】:
您确定需要在测试中使用这些依赖项吗?
根据单元测试理念,考虑使用一些模拟框架为您的 DbContext 和 IConfiguration 提供合适的行为和值的虚拟实例。
尝试研究 NSubstitute 或 Moq 框架。
【解决方案2】:
我发现创建“假”配置以传递给需要 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作为测试框架]