繁体   English   中英

依赖注入在.net core 2.0中进行统一测试

[英]unite testing in .net core 2.0 with Dependency Injection

我有采用DI方法的控制器。想使用单元测试来测试控制器的每个动作。 **控制器**

  public SearchController(ILookupSearch lookupSearch, IFullSearch fullSearch, IEmpUow uow, ILogger<SearchController> logger, TelemetryClient telemetryClient, IHostingEnvironment hostingEnvironment, IOptions<ConnectionStringsConfig> connectionString, IOptions<AppSettingsConfig> options)
    {
        this.LookupSearch = lookupSearch;
        this.FullSearch = fullSearch;
        this.EmpUow = uow;
        this.logger = logger;
        this.hostingEnvironment = hostingEnvironment;
        this.connectionString = connectionString.Value;
        this.appSettings = options.Value;
        this.telemetryClient = telemetryClient;
    }


    [Route("Test")]
        [ActionName("Test")]
        [HttpGet]
        public IActionResult Test()
        {
if(this.appsettings.enableDummyData){
            return this.SearchEmpData(new EmpIdQueryField() { Country = "Sweden", EMPID = 441150 });
           }
        }

调用转到控制器,但构造函数中的所有依赖项值均为null。

单元测试用例

   public async void Test1()
    {

        //Arrange

        Mock<IHostingEnvironment> hostingEnvironment = new Mock<IHostingEnvironment>();
        TelemetryClient telemetryClient = new TelemetryClient();
        Mock<ILogger<SearchController>> logger = new Mock<ILogger<SearchController>>();
        Mock<AppSettingsConfig> appSettings = new Mock<AppSettingsConfig>();

        Mock<IOptions<ConnectionStringsConfig>> connectionString = new Mock<IOptions<ConnectionStringsConfig>>();
        Mock<IOptions<AppSettingsConfig>> options = new Mock<IOptions<AppSettingsConfig>>();

        Mock<ILookupSearch> lookupSearch = new Mock<ILookupSearch>();
        Mock<IFullSearch> fullSearch = new Mock<IFullSearch>();
        Mock<IOneSoeUow> EmpUow = new Mock<IEmpUow>();

        //Act
        SearchController search = new SearchController(lookupSearch.Object, fullSearch.Object, oneSoeUow.Object, logger.Object, telemetryClient, hostingEnvironment.Object, connectionString.Object, options.Object);
        search.Test();

Test操作中,您将使用appsettings属性,需要在模拟对象中设置appsettings实例,

    Mock<IOptions<AppSettingsConfig>> options = new Mock<IOptions<AppSettingsConfig>>();
    options.Setup(e=>e.appsettings).Returns(new Appsettings(){ enableDummyData = true });

它将enableDummyData模拟为true,

同样,您需要设置在此操作或其他操作中使用的依赖项的所有其他属性

暂无
暂无

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

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