zoukankan      html  css  js  c++  java
  • .net core2 单元测试

    1.下载   https://marketplace.visualstudio.com/items?itemName=RandomEngy.UnitTestBoilerplateGenerator

    2.

    public static AppSettings GetSettings()
    {
    var envVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    var env = $"env: {envVariable}";
    var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddJsonFile($"appsettings.{envVariable}.json", optional: true)
    .Build();

    var result = config.Get<AppSettings>();
    return result;

    //var list = new List<string>();
    //config.GetSection("StringList").Bind(list);
    }
    }

    ConfigurationManager.AppSettings is a static dependency, so how can you unit test? Actually it's pretty easy - GetSection, Save, RefreshSection.
    The only caveat is you must have an app.config in your test project, even if it's empty.

    [TestClass]
    public class ChangeConfigurationTest
    {
        private const string Value = "Hello";
        private const string KeyValue = "MySetting";
     
        private static void ChangeConfiguration()
        {
            //the .config must exist (AppSettings doesn't have to be there).
            //if your test class doesn't have an App.config, this succeeds but the new appSetting is not loaded.
            var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetCallingAssembly().Location);
            var appSettings = (AppSettingsSection)config.GetSection("appSettings");
            appSettings.Settings.Clear();
            appSettings.Settings.Add(KeyValue, Value);
            config.Save();
            ConfigurationManager.RefreshSection("appSettings");
        }
     
        [TestMethod]
        public void TestMethod1()
        {
            var setting = ConfigurationManager.AppSettings[KeyValue];
            Assert.AreEqual(true, string.IsNullOrEmpty(setting));
            ChangeConfiguration();
            setting = ConfigurationManager.AppSettings[KeyValue];
            Assert.AreEqual(Value, setting);
        }
    }

    ConnectionStrings

    The corresponding code for a connection string.

    private static void ChangeConfiguration()
    {
        var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetCallingAssembly().Location);
        var connectionStrings = (ConnectionStringsSection)config.GetSection("connectionStrings");
        connectionStrings.ConnectionStrings["MyDatabase"]
            .ConnectionString = @"Data Source=C:Devcommands.sqlite";
        config.Save();
        ConfigurationManager.RefreshSection("connectionStrings");
    }

    3.

    var options = new AbOptions(){
        cc = new cc {
            D1 = "https://",
            D2 = "123145854170887"
        }
    };
    var mock = new Mock<IOptionsSnapshot<AbOptions>>();
    mock.Setup(m => m.Value).Returns(options);
    
    var service = new AbClass(mock.Object);

    4.

    ound it. i have to bind the instance

    var optionValue  = new MyOptions();
    _config.GetSection("MyOptions").Bind(optionValue);
     var options = Options.Create<MyOptions>(optionValue);
    

    or i can also do

     var optionValue = _config.GetSection("MyOptions").Get<MyOptions>();
     var options = Options.Create<MyOptions>(optionValue);


    var mock = new Mock<ILogger<BlogController>>();
    ILogger<BlogController> logger = mock.Object;
    
    //or use this short equivalent 
    logger = Mock.Of<ILogger<BlogController>>()
    
    var controller = new BlogController(logger);

    You probably will need to install Microsoft.Extensions.Logging.Abstractions package to use ILogger<T>.

    Moreover you can create a real logger:

    var serviceProvider = new ServiceCollection()
        .AddLogging()
        .BuildServiceProvider();
    
    var factory = serviceProvider.GetService<ILoggerFactory>();
    
    var logger = factory.CreateLogger<BlogController>();



    https://github.com/Moq/moq4/wiki/Quickstart

    https://martinwilley.com/net/code/appsettingtest.html

    Security Code Scan
  • 相关阅读:
    warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    Windows10+CLion+OpenCV4.5.2开发环境搭建
    Android解决部分机型WebView播放视频全屏按钮灰色无法点击、点击全屏白屏无法播放等问题
    MediaCodec.configure Picture Width(1080) or Height(2163) invalid, should N*2
    tesseract
    Caer -- a friendly API wrapper for OpenCV
    Integrating OpenCV python tool into one SKlearn MNIST example for supporting prediction
    Integrating Hub with one sklearn mnist example
    What is WSGI (Web Server Gateway Interface)?
    Hub --- 机器学习燃料(数据)的仓库
  • 原文地址:https://www.cnblogs.com/zwei1121/p/10154435.html
Copyright © 2011-2022 走看看