【问题标题】:unite testing in .net core 2.0 with Dependency Injection使用依赖注入在 .net core 2.0 中联合测试
【发布时间】:2018-05-21 04:46:33
【问题描述】:

我有使用 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 });
           }
        }

调用到控制器,但构造函数中的所有依赖值都是空的。

单元测试用例

   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();

【问题讨论】:

    标签: asp.net-mvc unit-testing .net-core moq xunit


    【解决方案1】:

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

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

    它将模拟enableDummyData 为真,

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

    【讨论】:

    • 尝试了同样的方法,但出现错误:'非虚拟(在 VB 中可覆盖)成员上的设置无效:a => a.SWITCH_ENABLE_DUMMY_DATA'
    猜你喜欢
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2016-05-22
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多