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:\Dev\commands.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

.net core2 单元测试的更多相关文章

  1. 从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 十六 ║Vue基础:ES6初体验 & 模块化编程

    缘起 昨天说到了<从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 十五 ║ Vue前篇:JS对象&字面量&this>,通过总体来看,好像大家对这一块不是很 ...

  2. net core体系-web应用程序-4asp.net core2.0 项目实战(CMS)-第一章 入门篇-开篇及总体规划

    .NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划   原文地址:https://www.cnblogs.com/yilezhu/p/9977862.html 写在前面 千呼万唤始出来 ...

  3. 用C#在Visual Studio写Javascript单元测试

    1.在vs创建一个标准的单元测试工程 2.引用nuget包:Edge.js 我是用的是6.11.2版本 3.编写JsRunner类 using EdgeJs; using System; using ...

  4. Intellij idea添加单元测试工具

    1.idea 版本是14.0.0 ,默认带有Junit,但是不能自动生成单元测试,需要下载JunitGererator2.0插件 2.Settings -Plugins,下载 JunitGenerat ...

  5. Python的单元测试(二)

    title: Python的单元测试(二) date: 2015-03-04 19:08:20 categories: Python tags: [Python,单元测试] --- 在Python的单 ...

  6. Python的单元测试(一)

    title: Python的单元测试(一) author: 青南 date: 2015-02-27 22:50:47 categories: Python tags: [Python,单元测试] -- ...

  7. javascript单元测试框架mochajs详解

    关于单元测试的想法 对于一些比较重要的项目,每次更新代码之后总是要自己测好久,担心一旦上线出了问题影响的服务太多,此时就希望能有一个比较规范的测试流程.在github上看到牛逼的javascript开 ...

  8. 使用NUnit为游戏项目编写高质量单元测试的思考

    0x00 单元测试Pro & Con 最近尝试在我参与的游戏项目中引入TDD(测试驱动开发)的开发模式,因此单元测试便变得十分必要.这篇博客就来聊一聊这段时间的感悟和想法.由于游戏开发和传统软 ...

  9. 我这么玩Web Api(二):数据验证,全局数据验证与单元测试

    目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试   一.模型状态 - ModelState 我理解 ...

随机推荐

  1. kettle之linux使用kettle

    Kettle可以在Window.Linux.Unix上运行,数据抽取高效稳定,使用之前需要准备环境. 准备java环境,这里就不赘述了,建议jdk7以上版本. 上传kettle压缩包,并解压,我解压的 ...

  2. 安装Feflow遇取的问题

    http://www.feflowjs.org/zh-cn/docs/ 在安装 npm install -g feflow-cli 是遇到这要一个问题 i C:\Program Files (x86) ...

  3. Hadoop学习笔记2 - 第一和第二个Map Reduce程序

    转载请标注原链接http://www.cnblogs.com/xczyd/p/8608906.html 在Hdfs学习笔记1 - 使用Java API访问远程hdfs集群中,我们已经可以完成了访问hd ...

  4. 基本的java加密算法MD5等等

    简单的java加密算法有: BASE64       严格地说,属于编码格式,而非加密算法 MD5             (Message Digest algorithm 5,信息摘要算法) SH ...

  5. leetcode 381.Insert Delete GetRandom

    这道题中要求使用O(1)的方法来删除和插入元素的,那么首先需要寻找到对应的元素,这个可以使用map的O(1)的查询时间的,然后是删除对应的元素的,那么可以根据 堆排序中类似的做法把最后面的元素插入到前 ...

  6. IS基础(函数片)

    函数基本介绍 为什么需要函数 之所以需要函数,是因为函数可以实现对代码的复用.相同的代码,我们不需要再重复书写,只需要书写一次就足够了.函数有些时候可以看做是一个暗箱.我们不需要知道函数内部是怎么实现 ...

  7. tensorflow 代码阅读

    具体实现: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/framework 『深度长文』Tensorflo ...

  8. django使用ckeditor上传图片

    1.在模型类中设置字段为富文本类型,这里需要注意引入的是RichTextUploadingField,以允许上传图片,需要和RichTextField区分开 from ckeditor_uploade ...

  9. 芯灵思Sinlinx A64 Linux&qt编译安装

    开发平台 芯灵思Sinlinx A64 内存: 1GB 存储: 4GB 详细参数 https://m.tb.cn/h.3wMaSKm 开发板交流群 641395230 前提条件搭建好CentOS环境 ...

  10. Nginx failing to load CSS and JS files (MIME type error)

    Nginx failing to load CSS and JS files (MIME type error) Nginx加载静态文件失败的解决方法(MIME type错误) 上线新的页面,需要在n ...