当前位置:网站首页>Summary of experience in using.Net test framework xUnit, mstest, specflow
Summary of experience in using.Net test framework xUnit, mstest, specflow
2022-07-24 16:26:00 【Guo Mahua】
Catalog
Unit test is to give input to the program , Judge whether the output meets the expectation
Not all code can write unit tests
Preface
xUnit and MSTest Both belong to the unit test framework , and Specflow Belong to BDD ( Behavior driven development ) frame .
In fact, the application of the three is very simple , But if you have never been exposed to specific examples , You may be confused from scratch .
I previously wrote an experimental distributed event bus , The above three frameworks are used , Want to learn .NET Students who test technology can go directly to MaH.EventBus - Repos (azure.com) See the sample .
Another two are recommended .NET Class libraries that are almost necessary for unit testing :NSubstitute,Shouldly. Both can help us conveniently Mock Interface or data , And making assertions .
unit testing
Brush over Leetcode All of my classmates know that , When we submit our answers , The system will tell us whether it is correct ; If it's wrong , There will be examples of data that cause errors , In fact, behind it is the function of unit testing .
Unit testing is : A given input , Judge whether the output meets the expectation
For specific algorithms ( Whether business algorithm or mathematical algorithm ) It is very useful to write unit tests with high coverage , It can find problems in the development process , It can also provide assurance for future code refactoring .
People often ignore the role of unit testing , In fact, the value of unit testing also meets the 28 law ,80% Test cases of may be like decorations , After writing, you never need to maintain . and 15% The test cases need to be modified with the change of business code , Perhaps only 5% Unit tests can really play a role in code refactoring .
Of course , There is no castle in the air , You can't build a house with only the second floor but no first floor , You can't just write that “5%” Test cases for .VS perhaps SonarQube Can provide us with unit test coverage analysis , Generally more than 80% Coverage is considered healthy .
Not all code can write unit tests
The object of unit test should be pure function , such as int Add(int a, int b) => a + b; This result is completely determined by the input function . stay VS2022 in , For functions that do not access any instance variables ,VS You will be prompted to change it to static, This kind of function belongs to pure function , It will also be very easy to write unit tests .
But for business projects , Non pure functions are unavoidable , for example , Anything that contains I/O The methods of operation are all non pure functions .
common I/O Operations include database connections , Network request , as well as Task.Delay,DateTime.Now etc. . We should try to encapsulate impure methods in a minimum range .
In addition, methods that rely on specific instances rather than interfaces are also non pure methods .
Unit testing should ensure purity , It means that the execution results must be consistent at any time , So we often need Mock Some data interfaces .
If you use it directly in your code DateTime.Now To make logical judgments , Then you have to refactor the current code , Wrap up the method of getting the current time , It is provided to the specific business logic through the interface , Otherwise, there is no way to write unit tests .
EF unit testing
Suppose you use EF Words , Then it will be very simple to write unit tests , You can use it directly Sqlite perhaps InMemory To create a memory based database , This makes it easy to use real DbContext To write test cases :
private static DemoDbContext CreateInMenoryDatabase()
{
var connection = new SqliteConnection("Filename=:memory:");
connection.Open();
var contextOptions = new DbContextOptionsBuilder<DemoDbContext>()
.UseSqlite(connection)
.EnableSensitiveDataLogging()
.Options;
var context = new DemoDbContext(contextOptions);
context.Database.EnsureCreated();
return context;
}xUnit and MSTest
These two project types can be found in VS Found in and created directly , After the creation, we can Test Explorer Find the created project and test cases .
If you are using VS Enterprise version , You can also use Live Unit Testing The function of , It will compile and run unit tests in real time when you write , And a blue or red check mark will be used on the left side of the code line to indicate whether the current line is overwritten , And whether the corresponding test cases are successful .
You can also generate and export containing branches , Test and analysis report of code line coverage and other information .
xUnit and MSTest The biggest difference in use lies in the different characteristics of test case methods , No more details here , Interested friends can go to the preface Code warehouse see .

Specflow
Specflow It aims to write test cases in natural language , So that non-technical personnel can understand . But it still needs technical implementation , And compared with unit testing , Often the test process and implementation are more complex .
establish Specflow The project needs to arrive first VS Install in the expansion Specflow plug-in unit
Let's show you Specflow Test Code style , It is recommended that you create Specflow Test Do it according to my project format , Writing Scenario,Steps It will be convenient when .


Specflow It is not only applicable to the test process , For example, based on Camunda BPMN Project created , And business scenarios that contain any process , It can be used for testing in any scenario .
I have this on top Demo The warehouse is right Specflow It's easy to use , Just made a LocalEventBus Usage scenarios of , A is given Specflow The structure of the project .
You can learn the usage of other commonly used keywords by yourself :
Given、When、Then、And、Background、Examples...
And placeholders that will be used when passing parameters :
'(.*)'
also Table Type parameters and the use of parsing methods :
[Given(@"Hello '(.*)'")]
public void Hello(string name, Table table)
{
var rows = table.CreateSet<T>();
}I'm just here to show , No specific explanation .
边栏推荐
- What does Baidu promote "delete and recall" mean?
- LaneATT
- Ligerui table control grid changes the color of rows (cells) according to the content
- LaneATT
- 124 maximum path sum in binary tree
- 'resultmap'must match' (constructor?, id*, result*, association*, collect problem solving
- Picture browser? QT can also be achieved!
- 2.19 haas506 2.0开发教程 - bluetooth - 蓝牙通信(仅支持2.2以上版本)
- Talk about C pointer
- TCP protocol debugging tool tcpengine v1.3.0 tutorial
猜你喜欢

TCP协议调试工具TcpEngine V1.3.0使用教程

ARP 入门

C# TCP客户端窗体应用程序异步接收方式

Power of leetcode 231.2

Talk about C pointer

Leetcode 220. duplicate element III exists
![[Nanjing Agricultural University] information sharing of postgraduate entrance examination and re examination](/img/1d/550a991385b842a21e2b301725407e.png)
[Nanjing Agricultural University] information sharing of postgraduate entrance examination and re examination

Leetcode 223. rectangular area

How to generate complex flow chart of XMIND

Parse string
随机推荐
矩阵的秩和图像的秩的一些了解
Four common post submission methods (application / x-www-form-urlencoded, multipart / form data, application / JSON, text / XML)
Huawei Kirin 985 mass production in the third quarter: TSMC 7Nm EUV process, integrated 5g baseband!
【LeetCode】Day102-螺旋矩阵 II
About SQL data query statements
TCP protocol debugging tool tcpengine v1.3.0 tutorial
'resultmap'must match' (constructor?, id*, result*, association*, collect problem solving
Can flush accounts be opened directly? Is it safe to open an account? How to open an account??
Code shoe set - mt2095 · zigzag jump
Code shoe set - mt2093 · palindrome digit
By default, the select drop-down box selects the solution ligerui that the selected attribute does not work
双指针滑动窗口法解析及LeetCode相关题解
Software - prerequisite software
Disassembly of Samsung Galaxy fold: the interior is extremely complex. Is the hinge the main cause of screen damage?
Qt键盘事件(一)——检测按键输入
Qt设计机器人仿真控制器——按键控制机器人关节转动
Codeworks round 693 (Div. 3) C. long jumps problem solution
Simple QQ? QT can also be achieved! (I)
【LeetCode】Day103-搜索二维矩阵 II
thinkphp3.2.5无法跳转到外部链接