.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:\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 单元测试的更多相关文章
- 从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 十六 ║Vue基础:ES6初体验 & 模块化编程
缘起 昨天说到了<从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 十五 ║ Vue前篇:JS对象&字面量&this>,通过总体来看,好像大家对这一块不是很 ...
- net core体系-web应用程序-4asp.net core2.0 项目实战(CMS)-第一章 入门篇-开篇及总体规划
.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划 原文地址:https://www.cnblogs.com/yilezhu/p/9977862.html 写在前面 千呼万唤始出来 ...
- 用C#在Visual Studio写Javascript单元测试
1.在vs创建一个标准的单元测试工程 2.引用nuget包:Edge.js 我是用的是6.11.2版本 3.编写JsRunner类 using EdgeJs; using System; using ...
- Intellij idea添加单元测试工具
1.idea 版本是14.0.0 ,默认带有Junit,但是不能自动生成单元测试,需要下载JunitGererator2.0插件 2.Settings -Plugins,下载 JunitGenerat ...
- Python的单元测试(二)
title: Python的单元测试(二) date: 2015-03-04 19:08:20 categories: Python tags: [Python,单元测试] --- 在Python的单 ...
- Python的单元测试(一)
title: Python的单元测试(一) author: 青南 date: 2015-02-27 22:50:47 categories: Python tags: [Python,单元测试] -- ...
- javascript单元测试框架mochajs详解
关于单元测试的想法 对于一些比较重要的项目,每次更新代码之后总是要自己测好久,担心一旦上线出了问题影响的服务太多,此时就希望能有一个比较规范的测试流程.在github上看到牛逼的javascript开 ...
- 使用NUnit为游戏项目编写高质量单元测试的思考
0x00 单元测试Pro & Con 最近尝试在我参与的游戏项目中引入TDD(测试驱动开发)的开发模式,因此单元测试便变得十分必要.这篇博客就来聊一聊这段时间的感悟和想法.由于游戏开发和传统软 ...
- 我这么玩Web Api(二):数据验证,全局数据验证与单元测试
目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试 一.模型状态 - ModelState 我理解 ...
随机推荐
- Linq语句的认识
LINQ语句的使用小结: 1.将数组看做一张表来查询的情况: from d in countyIsCityLevel where d.Equals(AreaCode) select d 2.只查询 ...
- 角度&弧度转换
一.角度转换为弧度 问题: 当使用Math类的三角函数的时候,所有的单位都是用弧度表示的.你有一个或多个角是用角度数度量的,并且希望把它们转换为弧度数,从而可以用它们作为Math类的成员. 解决方法: ...
- 把一个给定的值存储到一个整数中指定的几个位《C与指针5.8.5》
编写一个函数,把一个给定的值存储到一个整数中指定的几个位.它的原型如下: int store_bit_field(int original_value, int value_to_store, uns ...
- org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Cannot open con
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session f ...
- CSS学习笔记_day2
目录 一. css初识 二. 在HTML里面引入css的几种方式 1. 外部引入式 2.文档内嵌式 3. 行内式(元素内嵌式) 三. 选择器 四.盒模型 五.文档标准流 六.浮动 一. css初识 1 ...
- linux为什么要使用CentOS开发?
CentOS(Community Enterprise Operating System,社区企业操作系统)是Linux发行版之一,它是来自于Red Hat Enterprise Linux依照开放源 ...
- Maven配置pom.xml,正在下载时网络不佳下载失败的解决方案
环境:jdk1.7.0_17,Myeclipse 10,apache-maven-3.2.5 配置项目中pom.xml的dependencies时 ,如果本地仓库没有的话,就会自动下载.找不到仓库位置 ...
- CF285D.Permutation Sum
想了很久觉得自己做法肯定T啊,就算是CF机子的3s时限,但我毕竟是 O ( C(15,7)*7!*log ) .... 果然在n=15的点T了...贱兮兮地特判了15过掉了,结果发现题解说就是打表.. ...
- Mac使用
安装you-get: 用到mac下安装软件的工具:brew 百度搜brew到官网首页照说明在终端执行一段指令 安装方法:命令行输入 /usr/bin/ruby -e "$(curl -fsS ...
- 环境搭建--使用pytharm远程调试树莓派
对于Linux和文本编辑器不那么熟悉的小伙伴来说,直接在树莓派中写程序可谓是痛苦万分.本文将介绍如何使用PyCharm远程调试树莓派,并同步当前python文件到树莓派中. 配置环境 首先要在个人电脑 ...