【发布时间】:2018-12-26 10:33:01
【问题描述】:
在我的 Asp.net Core 2.0 应用程序中,我尝试对使用 Microsoft.Extensions.Configuration.IConfiguration 依赖注入的数据服务层(.Net 标准类库)进行单元测试。
我正在使用 XUnit,但不知道如何从我的单元测试类中传递 IConfiguration。我尝试了以下实现并收到错误
消息:以下构造函数参数没有匹配的夹具数据:IConfiguration 配置。
我对测试框架真的很陌生,甚至不知道是否可以像我在我的代码 sn-p 中尝试那样使用依赖注入。
我的单元测试类如下
public class SqlRestaurantDataCLUnitTest
{
private readonly IConfiguration configuration;
public SqlRestaurantDataCLUnitTest(IConfiguration configuration)
{
this.configuration = configuration;
}
[Fact]
public void AddTest()
{
var restaurantDataCL = new SqlRestaurantDataCL(configuration);
var restaurant = new Restaurant
{
Name = "TestName",
Cuisine = CuisineType.None
};
var result = restaurantDataCL.Add(restaurant);
Assert.IsNotType(null, result.Id);
}
}
我的数据服务层如下
public class SqlRestaurantDataCL : IRestaurantDataCL
{
private readonly IConfiguration configuration;
public SqlRestaurantDataCL(IConfiguration configuration)
{
this.configuration = configuration;
}
public Restaurant Add(Restaurant restaurant)
{
using (var db = GetConnection())
{
string insertSql = @"INSERT INTO [dbo].[RESTAURANTS]([Cuisine], [Name])
OUTPUT INSERTED.*
VALUES (@Cuisine, @Name)";
restaurant = db.QuerySingle<Restaurant>(insertSql, new
{
Cuisine = restaurant.Cuisine,
Name = restaurant.Name
});
return restaurant;
}
}
private IDbConnection GetConnection()
{
return new SqlConnection(configuration.GetSection(Connection.Name).Value.ToString());
}
}
public class Connection
{
public static string Name
{
get { return "ConnectionStrings: OdeToFood"; }
}
}
【问题讨论】:
-
你为什么还要传递
IConfiguration对象呢?您不应该有一个不错的 POCO,并将您的所有设置都作为属性吗?无论如何,只需创建一个实现IConfiguration并返回适合您测试的设置的对象。 -
@David 你能用一些代码示例解释一下吗?
-
我必须同意 DavidG 关于
IConfiguration依赖的观点。如何使用此依赖项。显示SqlRestaurantDataCL.GetConnection()。这可能最终成为 XY problem 中掩盖的设计问题 -
@Nkosi 我已经用 GetConnection() 代码更新了我的问题。
标签: unit-testing asp.net-core-mvc asp.net-core-2.0 xunit xunit.net