xUnit.NET to .NET CORE test

xUnit.NET to .NET CORE test

Original author of software craftsman

Meaning

XUNIT is a testing framework that can be tested against .net/core. Generally, the public method of the class is tested, that is, the behavior is tested. If it is a private method, the modifier needs to be changed to test.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-2tuTM5sP-1679620493695) (C:\Users\29310\AppData\Roaming\Typora\ typora-user-images\image-20230322135913491.png)]

Features

  • Support for multiple platforms/runtimes
  • ping for testing
  • data driven testing
  • Scalable

Automated test classification

  • Unit testing can test a certain class or method, has a high depth, and has little functional coverage of the application.
  • Integration tests have a better breadth and can test web resources, database resources, etc.
  • The subcutaneous test is performed on the web for node testing under the controller.
  • UI testing is the functional testing of the interface of the application.
  • In fact, unit testing and integration testing are commonly used.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-CmwyLtzH-1679620493696) (C:\Users\29310\AppData\Roaming\Typora\ typora-user-images\image-20230322140456987.png)]

Supported platforms

  • .Net Framework

  • .Net Core

  • .Net Standard: .NET Standard is a set of protocol specifications, unlike .NET Framework, which is a complete technical framework, while the former just defines a set of specifications, and .NET Standard class libraries that comply with this set of specifications can be used by different .NET framework references, such as .NET Core projects and .NET Framework projects can reference this class library.

    Detailed explanation of .NET Standard – Programmer Sought

  • UWP: Running on platforms such as Windows 10 Mobile/Surface (Windows Tablet PC)/PC/Xbox/HoloLens, UWP is different from exe applications on traditional PCs, and is also fundamentally different from apps that only apply to mobile phones. It is not designed for a certain terminal, but can run on all windows10 devices

  • Xamarin: is an open source platform for building modern, high-performance applications for iOS, Android, and Windows with .NET. Xamarin is an abstraction layer that manages the communication of shared code with the underlying platform code. Xamarin runs in a managed environment that provides conveniences such as memory allocation and garbage collection.

xUnit official website

Home > xUnit.net

Three phases of testing

Arrange: Do some prerequisites here. Such as creating object instances, data, inputs, etc.
Act: Execute production code here and return results. For example calling a method or setting a property.
Assert: Check the result here, and it will produce two results: pass or fail of the test.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-fdyhJtaR-1679620493697) (C:\Users\29310\AppData\Roaming\Typora\ typora-user-images\image-20230322142648593.png)]

Code

 [Fact]//Indicates that it is currently a test method. The marked test method cannot have method parameters
        public void ShouldAdd()
        {
            // Arrange
            var sut = new Demo.calculate();//sut - System Under Test

            // Act
            var result = sut. Add(2,3);

            // Assert
            Assert.Equal(5,result);//The first parameter is the result we want, the second is the test result
        }

Run

The first is to run it directly with vs.

The second type of cmd: find the current xunit file location dotnet test executes all tests, dotnet test –help help

Assert

Meaning

Assert evaluates the results of the test based on the return value of the code, the final state of the object, whether the event occurred, etc.
The result of Assert may be Pass or Fail
If all asserts pass, then the entire test passes.
If any assert fails, the result fails.

Type

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-kDdXZAv0-1679620493697) (C:\Users\29310\AppData\Roaming\Typora\ typora-user-images\image-20230322144717063.png)]

Question

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-RTWRYTBi-1679620493697) (C:\Users\29310\AppData\Roaming\Typora\ typora-user-images\image-20230322144824151.png)]

Code

using System;
using System.Collections.Generic;
using System. Text;
using Xunit;

namespace DemoTest
{
    public class PatientShould
    {
        /// <summary>
        /// bool type
        /// </summary>
        [Fact]
        public void Benewisture()
        {
            // Arrange
            var sut = new Demo. Patient();

            // Act
            var result = sut. IsNew;

            // Assert
            Assert. True(result);
        }
        /// <summary>
        /// string type
        /// </summary>
        [Fact]
        public void FullNameTest()
        {
            var sut = new Demo. Patient()
            {
                FirstName = "Lazy",
                LastName="Yangyang"
            };
            var result = sut.FullName;
            Assert.Equal("lazy",result);
            Assert.StartsWith("Lazy",result);
            Assert.EndsWith("Yangyang",result);
            Assert.Contains("Foreign",result);
        }
        /// <summary>
        /// type of data
        /// </summary>
        [Fact]
        public void bloodSugarValueTest()
        {
            var sut = new Demo. Patient();
            var result = sut. bloodSugar;
            Assert.Equal(4.9f,result);
            Assert.InRange(result,3.6f,6.1f);//interval value
        }
        /// <summary>
        /// class type
        /// </summary>
        [Fact]
        public void PatientIsNull()
        {
            var sut = new Demo. Patient();
            Assert. Null(sut. FirstName);
            //Assert. NotNull(sut. FirstName);
        }
        /// <summary>
        /// list type
        /// </summary>
        [Fact]
        public void HistroyAddOrSelect()
        {
            var sut = new Demo. Patient();
            sut.Histroy.Add("She Niu");
            sut.Histroy.Add("Social terror");
            sut.Histroy.Add("Digging wild vegetables");
            sut.Histroy.Add("Love Brain");

            List<string> Health = new List<string>()
            {
                "She Niu",
                "Social fear",
                "Digging wild vegetables",
                "Love Brain"
            };

            Assert.Contains("Digging wild vegetables", sut.Histroy);
            Assert.DoesNotContain("IKUN",sut.Histroy);
            //Assert.Contains(sut.Histroy,u=>u.StartsWith("Bull"));
            Assert.Contains(sut.Histroy,u=>u.Length>=2);
            Assert. Equal(Health, sut. Histroy);
        }
        /// <summary>
        /// Determine whether it is an actual column
        /// </summary>
        [Fact]
        public void BeAPerson()
        {
            var p = new Demo. Patient();
            var pr = new Demo. Person();
            Assert.IsType<Demo.Patient>(p);
            Assert.IsNotType<Demo.Person>(p);
            Assert.IsAssignableFrom<Demo.Person>(p);
            Assert. NotSame(p,pr);
            //Assert.Same(p, pr);//Is it an actual column

        }
        /// <summary>
        /// exception
        /// </summary>
        [Fact]
        public void ExpretionError()
        {
            var ex = Assert.Throws<InvalidOperationException>(()=>new Demo.Patient().NotMessage());
            Assert.Equal("Cannot execute this thing", ex.Message);
        }
        /// <summary>
        /// Whether the event is executed
        /// </summary>
        [Fact]
        public void functionExecution()
        {
            var p = new Demo. Patient();
            Assert. Raises<EventArgs>(
                handler => p. PatienSlept + = handler,
                handler => p. PatienSlept -= handler,
                () => p.Sleep());
        }
        /// <summary>
        /// Whether the event has changed
        /// </summary>
        [Fact]
        public void functionUpdate()
        {
            var p = new Demo. Patient();
            Assert.PropertyChanged(p, nameof(p.HeartBeatRate), () => p.IncreaseHeartBeatRate());
        }
    }
}

using Hangfire. Annotations;
using System;
using System.Collections.Generic;
using System. ComponentModel;
using System.Runtime.CompilerServices;
using System. Text;

namespace Demo
{
    public class Patient: Person, INotifyPropertyChanged
    {
        public Patient()
        {
            IsNew = true;
            bloodSugar = 4.9f;//Record here what the addition of f means to prevent loss of precision
            History = new List<string>();
        }
        public string FullName => $"{FirstName}{LastName}";
        public int HeartBeatRate { get; set; }
        public bool IsNew { get; set; }
        public float bloodSugar { get; set; }
        public List<string> Histroy { get; set; }
        public event EventHandler<EventArgs> PatienSlept;//event event event delegation type
        public event PropertyChangedEventHandler PropertyCyhanged;
        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void Onchangenoti([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public void OnPatienSlept()
        {
            PatienSlept?.Invoke(this,EventArgs.Empty);//Provide data for delegate events without data
        }
        public void Sleep()
        {
            OnPatienSlept();
        }
        public void IncreaseHeartBeatRate()
        {
            HeartBeatRate = CalculateHeartBeatRate() + 2;
            Onchangenoti(nameof(HeartBeatRate));
        }
        private int CalculateHeartBeatRate()
        {
            var random = new Random();
            return random. Next(1,100);
        }
        public void NotMessage()
        {
            throw new InvalidOperationException("Cannot execute this thing");
        }
         
    }

 
}

Test group

[Trait(‘name’,’value’)]

Select a feature in the group and apply it to the class and method

cmd command: dotnet test –filter Category=New single dotnet test –filter “Category=New|Category=Name”

Ignore

[Fact(Skip=”No need to run this test”)]

Custom output information

cmd command: dotnet test –filter Category=New –logger:trx

Refactor code

write prompt

 private readonly ITestOutputHelper _outHelp;
  _task = fixture. Task;

IDisposable implements the interface

 public void Dispose()
        {
            _outHelp.WriteLine("clean up resources");
        }

Shared classes

[Collection("Long Time Task Collection")]

Data sharing

[InlineData()]

 //The first data source
        [Theory]
        [InlineData(1,2,3)]
        [InlineData(4,2,6)]
        [InlineData(5,2,7)]
        [InlineData(6,2,8)]
        public void ShouldAdd(int x,int y,int expression)
        {
            var sut = new Demo. calculate();
            var result = sut. Add(x, y);
            Assert. Equal(expression, result);
        }

[MemberData(nameof(calculateDate.TestDate),MemberType=typeof(calculateDate))]

 //Second data source
        [Theory]
        [MemberData(nameof(calculateDate.TestDate),MemberType=typeof(calculateDate))]
        public void ShouldAdd2(int x, int y, int expression)
        {
            var sut = new Demo. calculate();
            var result = sut. Add(x, y);
            Assert. Equal(expression, result);
        }

External data sources

First declare a csv file to write data (change the attribute to copy)

Then write a class to accept the data

 /// <summary>
    /// Read the file and return the data set
    /// </summary>
    public class CalculatorCsvData
    {
        public static IEnumerable<object[]> TestData
        {
            get
            {
                //Read the data in the csv file and convert it
                string[] csvLines = File.ReadAllLines("TestData.csv");
                var testCases = new List<object[]>();
                foreach (var csvLine in csvLines)
                {
                    IEnumerable<int> values = csvLine.Trim().Split(',').Select(int.Parse);
                    object[] testCase = values.Cast<object>().ToArray();
                    testCases. Add(testCase);
                }
                return testCases;
            }
        }
    }

Custom attributes are inherited from DataAttribute

using System;
using System.Collections.Generic;
using System. Reflection;
using System. Text;
using Xunit.Sdk;

namespace DemoTest
{
    public class CalculatorDataAttribute : DataAttribute
    {
        public override IEnumerable<object[]> GetData(MethodInfo testMethod)
        {
            yield return new object[] { 0, 100, 100 };//yield provides the next element
            yield return new object[] { 1, 99, 100 };
            yield return new object[] { 2, 98, 100 };
            yield return new object[] { 3, 97, 100 };
        }
    }
}


est
{
public class CalculatorDataAttribute : DataAttribute
{
public override IEnumerable GetData(MethodInfo testMethod)
{
yield return new object[] { 0, 100, 100 };//yield provides the next element
yield return new object[] { 1, 99, 100 };
yield return new object[] { 2, 98, 100 };
yield return new object[] { 3, 97, 100 };
}
}
}