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

转载于:https://www.cnblogs.com/zwei1121/p/10154435.html

.net core2 单元测试相关推荐

  1. springboot项目使用junit4进行单元测试,maven项目使用junit4进行单元测试

    首先,maven项目中引入依赖 <dependency><groupId>junit</groupId><artifactId>junit</ar ...

  2. 写算子单元测试Writing Unit Tests

    写算子单元测试Writing Unit Tests! 一些单元测试示例,可在tests/python/relay/test_op_level3.py中找到,用于累积总和与乘积算子. 梯度算子 梯度算子 ...

  3. 写单元测试应该注意什么

    写单元测试应该注意什么 转载于:https://www.cnblogs.com/yishenweilv/p/10899695.html

  4. Atitti mybatis的单元测试attilax总结

    Atitti mybatis的单元测试attilax总结 版本mybatis 3.2.4 /palmWin/src/main/java/com/attilax/dao/mybatisTest.java ...

  5. java 中的单元测试_浅谈Java 中的单元测试

    单元测试编写 Junit 单元测试框架 对于Java语言而言,其单元测试框架,有Junit和TestNG这两种, 下面是一个典型的JUnit测试类的结构 package com.example.dem ...

  6. android 找不到类文件,Android Studio单元测试找不到类文件!

    就是一个方法里面逻辑比较多,查数据库,循环等等.比较复杂,我想测试一下他.是没有返回值的,我想看运行完成之后看看最后里面的变量是不是对的 如果跑整个程序的话就太慢了, 编译,运行, 登陆 等等.太长了 ...

  7. java单元测试启动类配置_Springboot 单元测试简单介绍和启动所有测试类的方法

    最近一段时间都是在补之前的技术债,一直忙着写业务代码没有注重代码的质量,leader也在强求,所有要把单元测试搞起来了 我把单元测试分为两种 一个是service的单元测试,一个是controller ...

  8. JUnit单元测试依赖包构建路径错误解决办法

    JUnit单元测试依赖包构建路径错误解决办法: 选中报错的项目文件夹→右击选择属性(ALT+Enter)→java构建路径→库→添加库→JUnit→选择合适的Junit库版本.

  9. kotlin + springboot 整合redis,Redis工具类编写及单元测试

    参考自:  https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html 1.maven依赖 <?xml ve ...

最新文章

  1. 接口文档-swagger-bootstrap
  2. 8.1 概述-机器学习笔记-斯坦福吴恩达教授
  3. Ngrok: 使用 Ngrok 实现内网穿透
  4. 分布式ID生成器(来源:架构师之路,2017-06-25 58沈剑 架构师之路)
  5. python找不到csv文件_Python如何读取csv文件
  6. PostgreSQL数据库 OLTP高并发请求性能优化
  7. ​50 年来最具影响力的十大编程语言!
  8. Jquery Cookbook摘要之使用上下文参数
  9. 各种常用的JSON接口
  10. 游戏开发关卡设计(16)
  11. matlab动态更新数组值,Matlab动态数组实现
  12. 三分钟带你快速了解网站开发的整个流程
  13. 微信公众平人数多服务器会崩溃吗,微信公众号平台推新功能 再也不怕文章崩溃...
  14. 数据分析统计学基础笔记
  15. Mac下的Kali虚拟机的安装
  16. 复旦大学计算机应用复试线,2019年复旦大学考研复试分数线已出现
  17. 大数据处理技术的总结与分析
  18. Coursera-MachineLearning-Week2编程题目整理
  19. Pony.ai 自动驾驶
  20. JS实现抽奖代码(0-999随机数开始暂停抽奖按钮)

热门文章

  1. SQL 的 left join 和 right join
  2. spark 如何用netty实现akka的actor模型
  3. linux 树型显示文件 tree ls tree 命令
  4. 信用评分系统运行原理下篇
  5. Spring Cloud Sleuth 原理简介和使用
  6. RocketMQ如何保证消息不丢失(消息可靠性)
  7. Java高并发入门-线程初步
  8. 内存管理单元MMU简介
  9. 如何开启和使用windows 10中的Hyper-v
  10. 关于JVM的几个问题