我正在为API应用程序的业务层进行单元测试,无法正确模拟依赖关系/配置。
public class CategoryBusiness : BusinessBase, ICategoryBusiness
{
private IApiRequestHelper _Api { get; set; }
public CategoryBusiness(IApiRequestHelper Api)
{
_Api = Api;
}
public async Task<CategoryCollection> GetAllAsync(string client)
{
var method = "get_module_fields";
var payload = new
{
session = "",
module_name = "Tickets",
select_fields = new string[] { "product", "exceptions_list_c" }
};
var response = await _Api.ExecuteCommandAsync(method, payload, client);
// more stuff
return categories;
}
}
public class ApiRequestHelper : IApiRequestHelper
{
private readonly IConfiguration _configuration;
public ApiRequestHelper(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task<Dictionary<string, dynamic>>
ExecuteCommandAsync(string method, object payload, string client)
{
var username = _configuration["Api:Username"];
var pass = _configuration["Api:Password"];
//
// more stuff
//
}
}
这些都已在Bootstrap.cs中注册
private static void RegisterBusinessDependencies(IServiceCollection
services, IConfiguration configuration)
{
services.AddScoped(o => new ApiRequestHelper(configuration));
services.AddScoped<ICategoryBusiness, CategoryBusiness>();
services.AddScoped<IApiRequestHelper, ApiRequestHelper>();
}
我正在按照此博客文章https://weblog.west-wind.com/posts/2018/Feb/18/Accessing-Configuration-in-NET-Core-Test-Projects中的步骤访问测试项目中的配置值。但是,我无法正确模拟依赖于IConfiguration实例的ApiRequestHelper。这些是我的测试课程以及我想出的解决方法:
[TestFixture]
public class CategoryBusinessTests
{
private FSIConfiguration _configuration;
private CategoryBusiness _categoryBusiness;
[SetUp]
public void Init()
{
_configuration = TestHelper.GetApplicationConfiguration(TestContext.CurrentContext.TestDirectory);
ApiRequestHelper helper = new ApiRequestHelper(_configuration);
_categoryBusiness = new CategoryBusiness(helper);
}
[Test]
public async Task GetAllAsync()
{
var result = await _categoryBusiness.GetAllAsync("");
var type = result.Primary.FirstOrDefault().GetType();
Assert.That(type, Is.EqualTo(typeof(Category)));
}
}
public class TestHelper
{
public static IConfigurationRoot GetIConfigurationRoot(string outputPath)
{
return new ConfigurationBuilder()
.SetBasePath(outputPath)
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
}
public static TestConfiguration GetApplicationConfiguration(string outputPath)
{
var configuration = new TestConfiguration();
var iConfig = GetIConfigurationRoot(outputPath);
iConfig.GetSection("Api").Bind(configuration);
return configuration;
}
}
public class TestConfiguration : IConfiguration
{
public string this[string key]
{
get { return this.GetType().GetProperty(key.Split(":")[1]).GetValue(this).ToString(); }
set { throw new NotImplementedException(); }
}
public string Url { get; set; }
public string Username { get; set; }
public string Password { get; set; }
// extra interface implementation
}
这是可行的,但是我觉得这不是实例化ApiRequestHelper(和CategoryBusiness)类的正确方法。有人能指出我正确执行操作的正确方向吗?