如何将服务配置传递给Xunit项目测试控制器?

我目前有以下设置。

启动类: Startup.cs

public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.Configure(Configuration.GetSection("AzureStorageConfig")); services.AddTransient(); } //other config settings ... } 

类: AzureStorageConfig

 //store the azure account details etc... public class AzureStorageConfig { public string AzureURL { get; set; } public string StorageConnectionString { get; set; } public string AccountName { get; set; } } 

接口类: IAzureService

 public interface IAzureService { Task UploadFileAsync(AzureStorageConfig _storageConfig, string filename); Task DeleteFile(AzureStorageConfig _storageConfig, string filename); } 

Azure类:上面的接口使用的AzureService

 public class AzureService : IAzureService, IDisposable { // Here implemented above service methods.. public Task UploadFileAsync(AzureStorageConfig _storageConfig, string filename) { //... } Task DeleteFile(AzureStorageConfig _storageConfig, string filename) { //... } } 

图像控制器: ImageController.cs

 [Produces("application/json")] [Route("api/Images")] public class ImagesController : Controller { #region Private properties private readonly ApiDbContext _context; private readonly IMapper _mapper; private AzureStorageConfig _storageConfig; public readonly IAzureService _azureService; #endregion #region Constructor public ImagesController(ApiDbContext context, IMapper mapper, IOptions storageConfig, IAzureService azureService) { _context = context; _mapper = mapper; _storageConfig = storageConfig.Value; _azureService = azureService; } // other POST and Delete methods written public async Task PostImage(Guid Id, [FromForm] ICollection files) { // here used _storageConfig objects to use account key and names... } } 

使用xunit在下面的类(TEST库)中的主要问题

类: ImageControllerTest

 [Collection("TestDb")] public class ImageControllerTest : IClassFixture { private ImagesController _controller; private DatabaseFixture _fixture; private InitializeAutoMap _initialize; public ImageControllerTest(DatabaseFixture fixture, InitializeAutoMap initialize) { this._fixture = fixture; this._initialize = initialize; // How to pass service object and StorageConfig to the main //ImageController from this TestController for testing. _controller = new ImagesController(_context, _initialize.InstanceMapper, /**/, /**/ ); } // other [Fact] testing done. // other codes.. } 

如何将其注入Xunit ImageControllerTest构造函数。

  • storageConfig类对象和
  • IAzureService对象从Xunit ImageControllerTest方法进入ImageController。

如果您有想法或解决方案,请与我分享。