In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
How to use xUnit for. Net core program unit testing, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
one。 Why should I write an automated test program (Automated Tests)?
Can be tested frequently
Testing can be done at any time, or on schedule, for example, automated testing can be done in the middle of the night.
It must be faster than manual testing.
Errors can be found more quickly.
It's basically very reliable.
The test code is closely integrated with the production code.
Make the development team happier!
Classification of automated tests:
The vertical axis represents the depth of the test, that is, the degree of detail of the test.
The horizontal axis indicates the degree of coverage of the test.
Unit Test unit testing, which can test a class, or a function of a class, it has a good depth, but it does not have a good coverage for the whole application.
Integration Test integration testing, which is not as detailed as unit testing, but has relatively good test coverage. For example, it can test combinations of functions, as well as external resources such as databases or file systems.
Subcutaneous Test hypodermic testing, which works on the lower layer of the UI layer, also means that it has good coverage for the entire application, but not good depth. For the application of the MVC structure, it is for the test just below the Controller, and for Web service, it is the test for the layer below the node.
UI testing, which covers a wide range of tests, is tested directly from the UI level, but the depth is not good.
In terms of speed, the unit is the fastest, while the UI test is the slowest.
UI testing is the worst in terms of vulnerability, and it is very likely that the test code needs to be modified after the program is modified, and unit testing is the best.
Is it a test behavior or a test private method (private method)?
Public void IncreaseHeartBeatRate ()
{
HeartBeatRate = CalculateHeartBeatRate () + 2
}
Private int CalculateHeartBeatRate ()
{
Var random = new Random ()
Return random.Next (1,100)
}
In most cases, unit tests should be tested against the behavior of the class, that is, the public method. Of course, it is also purely in a different point of view.
If you want to test the private method, there are many disadvantages:
First of all, the access restriction of the method needs to be changed from private to public, which destroys the object-oriented encapsulation.
Furthermore, this actually tests the specific implementation details of the class, not the behavior of the class. If we want to ReFactor the interior of the class, it destroys the test and causes the test to be refactored as well. If the private method must be tested, it is recommended that you first change the private modifier to internal, and then modify the AssemblyInfo.cs of the project (project), which is under the project's Debug or Release folder. The code is as follows:
[assembly: InternalsVisibleTo ("Hospital.Tests")]
This means that the Hospital.Tests test project can access the internal method of the project's production code (production code).
Three stages of testing AAA
Arrange, here are some preliminary settings. Such as creating object instances, data, input, and so on.
Act, where the production code is executed and the result is returned. For example, call a method or set a property (Properties).
Assert, check the results here. The test passed or failed.
XUnit.net
Official website: https://xunit.github.io/
XUnit is a testing framework that can be tested against. Net / core.
The test project needs to refer to the project to test it, and the test project also needs to reference the xUnit library. After the test is written, run the test with Test Runner. Test Runner can read the test code, and will know the test framework we are using, then execute it, and display the results. Currently available Test Runner includes Test Explorer that comes with vs, or dotnet core command line, as well as third-party tools, such as resharper, and so on.
Platforms supported by xUnit:
.net full, .net core, .net standard, uwp, xamarin.
An example of xUnit:
[Fact]
Public void TestIncreaseHeartBeatRate ()
{
Var patient = new Patient (); / / Arrange
Patient.IncreaseHeartBeatRate (); / / Act
Assert.InRange (patient.HeartBeatRate, 40,100); / / Assert
}
Install and configure xUnit.neta. Use Visual Studio 2017
First, create a C # library project called Hospital (there is a spelling mistake in the screenshot below, which should be Hospital), and then create a xUnit Test project called Hospital.Tests:
You can see that Hospital.Tests has included these libraries:
Then add a reference to the Hospital project for Hospital.Tests.
b. Use the .net core command line
First remove the Hospital.Tests project you just created (the directory needs to be deleted manually).
Then open the project location:
Press and hold shift to open the command line:
Create a project from the command line:
Create the Hospital.Tests directory, enter the directory, and use the command dotnet new xunit to create the xUnit unit test project.
Add a reference to the project:
Finally, add the project to the solution:
Go back to the VS interface and prompt to reload:
After confirmation, the solution structure in VS is as follows:
Do the first test.
Do some refactoring of the file name of the test project, write the following code, and Build:
From Test Explorer we can see a project to be tested.
Here, we can group and sort the test projects, as shown in the figure:
To run all the tests, click the Run All button above. If you want to run a single test, right-click and select Run Selected Tests:
After running, you can see the result, Passed:
We can also test from the command line:
Go to the Tests directory, execute the dotnet test command, and all tests will be discovered and executed:
Because we didn't write any Assert in the test method, the test must have passed, but the test is also an invalid test.
Assert
What does Assert do? Assert evaluates the results of the test based on the return value of the code, the final state of the object, the occurrence of events, and so on. The result of Assert may be Pass or Fail. If all the asserts is pass, the whole test is pass; if there is any assert fail, the test is fail.
XUnit provides the following types of Assert:
Boolean:True/False
String: equal / unequal, whether it is empty, with.. Start / end, whether to include substrings, match regular expressions
Numerical type: equal / unequal, whether within a certain range, floating-point accuracy
Collection: whether the content is equal, whether it contains an element, whether it contains an element that meets a certain condition (predicate), and whether all elements satisfy a certain assert
Raised events:Custom events,Framework events (e.g. PropertyChanged)
Object Type: whether it is a certain type, whether a certain type or inheritance is related to a certain type
How many asserts should there be in a test?
One recommended approach is to have only one assert in each test method.
Another suggestion is that there can be multiple asserts in each test, as long as the asserts is for the same behavior.
The first Assert
Target class:
Public class Patient
{
Public Patient ()
{
IsNew = true
}
Public string FirstName {get; set;}
Public string LastName {get; set;}
Public string FullName = > $"{FirstName} {LastName}"
Public int HeartBeatRate {get; set;}
Public bool IsNew {get; set;}
Public void IncreaseHeartBeatRate ()
{
HeartBeatRate = CalculateHeartBeatRate () + 2
}
Private int CalculateHeartBeatRate ()
{
Var random = new Random ()
Return random.Next (1,100)
}
}
Test class:
Public class PatientShould
{
[Fact]
Public void HaveHeartBeatWhenNew ()
{
Var patient = new Patient ()
Assert.True (patient.IsNew)
}
}
Run the test:
The results were as expected and the test passed.
If changed to Assert.False ():
Test Fail.
String Assert
Test whether the string is equal:
[Fact]
Public void CalculateFullName ()
{
Var p = new Patient
{
FirstName = "Nick"
LastName = "Carter"
}
Assert.Equal ("Nick Carter", p.FullName)
}
Then you need to Build so that VS Test Explorer can discover the new test.
Run the test, and the result Pass:
Also change the Patient class (don't forget to Build it) so that the result fails:
You can see the expected value and the actual value from the failure message.
StartsWith, EndsWith
[Fact]
Public void CalculateFullNameStartsWithFirstName ()
{
Var p = new Patient
{
FirstName = "Nick"
LastName = "Carter"
}
Assert.StartsWith ("Nick", p.FullName)
}
[Fact]
Public void CalculateFullNameEndsWithFirstName ()
{
Var p = new Patient
{
FirstName = "Nick"
LastName = "Carter"
}
Assert.EndsWith ("Carter", p.FullName); e)
}
Build, and then Run Test, resulting in Pass:
Ignore case ignoreCase:
The default Assert for string is case-sensitive, so it fails:
You can add a parameter ignoreCase to true for these methods, and case is ignored:
Contains the substring Contains
[Fact]
Public void CalculateFullNameSubstring ()
{
Var p = new Patient
{
FirstName = "Nick"
LastName = "Carter"
}
Assert.Contains ("ck Ca", p.FullName)
}
Build, test result Pass.
Regular expressions, Matches
Test whether the initials of First name and Last name are capitalized:
[Fact]
Public void CalculcateFullNameWithTitleCase ()
{
Var p = new Patient
{
FirstName = "Nick"
LastName = "Carter"
}
Assert.Matches ("[Amurz] {1} {Amurz} + [Amurz] {1} [Amurz] +", p.FullName)
}
Build, the test passed.
Numerical Assert
First add a property: BloodSugar for the Patient class.
Public class Patient
{
Public Patient ()
{
IsNew = true
_ bloodSugar = 5.0f
}
Private float _ bloodSugar
Public float BloodSugar
{
Get {return _ bloodSugar;}
Set {_ bloodSugar = value;}
}
...
Equal:
[Fact]
Public void BloodSugarStartWithDefaultValue ()
{
Var p = new Patient ()
Assert.Equal (5.0, p.BloodSugar)
}
Build, the test passed.
Range, InRange:
First add a method to the Patient class where the patient's blood sugar rises after a meal:
Public void HaveDinner () {
Var random = new Random (); _ bloodSugar + = (float) random.Next (1, 1000) / 100; / / should be 1000}
Add test:
[Fact]
Public void BloodSugarIncreaseAfterDinner ()
{
Var p = new Patient ()
P.HaveDinner ()
/ / Assert.InRange (p.BloodSugar, 5, 6)
Assert.InRange (p.BloodSugar, 5,6)
}
Build,Run Test, result Fail:
You can see the expected Range and the actual value, which is good. If you use Assert.True (xx > = 5 & & xx)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.