C# 8 & How to carry out unit test for C 9 function? Here's the answer
The leaves fall with the rain 2021-05-04 09:09:34

Click on “ Learn more about ” Get tools

Telerik DevCraft Include a complete product stack to build your next Web、 Mobile and desktop applications . It USES HTML And each .NET Platform UI library , Speed up development .Telerik DevCraft Provides the most complete toolbox , For building modern and future oriented business applications , At present UI for ASP.NET MVC、Kendo UI、UI for ASP.NET AJAX、UI for WPF、UI for Xamarin、Reporting And many other controls .

According to the survey ,C# Still one of the most popular programming languages , It's powerful , Easy to learn and constantly improve and develop . New features have been added to the language in recent years , The new version iterates continuously ——C# 7, C# 8, C# 9.

Progress Telerik The product is always related to .NET Keep up with the latest features in the world ,C#9 and JustMock No exception . Most of the new features are easy to use in unit testing and simulation , But this article will show you something interesting , So that you can easily use it in unit testing C# function .

  • Static local functions (C#8)
  • Asynchronous methods
  • Record
  • initialization
  • Pattern matching

To illustrate this , We will use Foo class .

public class Foo{public Foo(){this.Bar = 10;this.DateTime = new DateTime(2021, 1, 1);}public int Bar { get; init; }public DateTime DateTime { get; init; }public bool IsInRange(int i) =>i is (>= 1 and <= 10) or (>= 100 and <= 200);}public record Person{public string LastName { get; }public string FirstName { get; }public Person(string first, string last) => (FirstName, LastName) = (first, last);}public record Teacher : Person{public string Subject { get; }public Teacher(string first, string last, string sub): base(first, last) => Subject = sub;}

Be careful : To run the example , You need to download and install from here JM.

1. use first Mock.Local Simulate static function


public void TestStaticLocal(){// Arrangevar sut = new Foo();// Here is how to mock the static function Mock.Local.Function.Arrange<int>(sut, "MethodWithStaticLocal", "Add", Arg.Expr.AnyInt, Arg.Expr.AnyInt).Returns(1);// Actvar result = sut.MethodWithStaticLocal();// AssertMock.Assert(sut);Assert.AreNotEqual(12, result);}

2. Asynchronous flow

from C#8.0 Start , You can create and use streams asynchronously . There are three details about the method of returning asynchronous flows :

  • use async Modifier declaration
  • It returns a IAsyncEnumerable<T>
  • The method includes yield return sentence , To return subsequent elements in the asynchronous flow

In the following example , You can see examples of this approach and how to simulate it :


public async Task TestAsyncEnumFromArray(){// Arrangevar expected = new int[] { 10, 20, 30 };Mock.Arrange(() => Foo.GetAsyncCollection()).Returns(expected.GetEnumerator().ToAsyncEnumerable<int>());// Actvar result = Foo.GetAsyncCollection();// AssertMock.Assert<Foo>();int index = 0;await foreach (var number in result){Assert.AreEqual(expected[index++], number);}}

3. Just initialize the setter

only Init Provides a consistent syntax for initializing members of an object , The property initializer makes it clear which value is setting which property , The disadvantage is that these properties must be settable . from C#9.0 Start , You can create... For attributes and indexers init accessor , Instead of setting up accessors .

How to simulate it when writing a test ? Use JustMock Of Mock.NonPublic.ArrangeSet Method .


public void TestInit(){// Arrange var fooMock = Mock.Create<Foo>();bool properyInitCalled = false;Mock.NonPublic.ArrangeSet(fooMock, "Bar", 10).IgnoreInstance().DoInstead(() => properyInitCalled = true);// Act var foo = new Foo();// Assert Assert.IsTrue(properyInitCalled);}



public void TestInit2(){// Arrange var fooMock = Mock.Create<Foo>(Constructor.NotMocked);dynamic fooMockWrapper = Mock.NonPublic.Wrap(fooMock);Mock.NonPublic.Arrange(fooMockWrapper.Bar = 10).IgnoreInstance().MustBeCalled();// Act var foo = new Foo();// Assert Mock.NonPublic.Assert(fooMockWrapper.Bar = 10, Occurs.Once());}

4. Pattern matching

C# Another great addition to the language is pattern matching , the C# Developers provide more creativity and flexibility !

As the document says , Basically you want to look at a given structure , Then identify and determine its structure according to its appearance , Then you can use it immediately .

To show you how to use InRange Methods to simulate these functions , This is our pattern matching example , And then there's the next test :

public bool IsInRange(int i) =>i is (>= 1 and <= 10) or (>= 100 and <= 200);...[TestMethod]public void Mock_PatternMatchingTest(){// Arrangevar foo = Mock.Create<Foo>(Behavior.CallOriginal);Mock.Arrange(() => foo.IsInRange(Arg.AnyInt)).Returns(true);// Actvar result20 = foo.IsInRange(20);var result150 = foo.IsInRange(150);//AssertAssert.AreEqual(true, result20);Assert.AreEqual(true, result150);}

I know that reading code is not the same as running code , So use it and use examples , Follow these steps :

  • download JustMock
  • Install it
  • Download the project from here

Stay up to date Kendo UI The latest news , Please pay attention to Telerik Chinese net !

本文为[The leaves fall with the rain]所创,转载请带上原文链接,感谢