Good software comes with tests. Fortunately, Visual Studio 2019 provides quite nice ways to test the software you are creating. One of these is xUnit – xunit.net. Thus, I have decided to make a video, showing how to implement xUnit in a Visual Studio project and what are the pluses, from having tests:
In the video, I am implementing the calculation of the Fibonacci sequence through 2 different methods – one with recursion (commented out in the code below) and one quickly looping through the numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using System.Collections.Generic; using System.Text; namespace FibonacciWithXUnit { public class Fibonacci { public long Calculate(int position) { //if (position == 1) return 1; //if (position == 2) return 1; //return Calculate(position - 1) + Calculate(position - 2); if (position == 1 || position == 2) { return 1; } int fib1 = 1; int fib2 = 1; int result = -1; for (int i = 3; i <= position; i++) { result = fib1 + fib2; fib1 = fib2; fib2 = result; } return result; } } } |
I have decided to use 4 tests only – 2 for the first two corner cases and 2 others:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
using FibonacciWithXUnit; using System; using Xunit; namespace XUnitTestFibonacci { public class FibonacciTest { [Fact] public void Fibonacci001() { //Arrange var fib = new Fibonacci(); //Act var result = fib.Calculate(1); //Assert Assert.Equal(1, result); } [Fact] public void Fibonacci002() { //Arrange var fib = new Fibonacci(); //Act var result = fib.Calculate(2); //Assert Assert.Equal(1, result); } [Fact] public void Fibonacci005() { //Arrange var fib = new Fibonacci(); //Act var result = fib.Calculate(5); //Assert Assert.Equal(5, result); } [Fact] public void Fibonacci012() { //Arrange var fib = new Fibonacci(); //Act var result = fib.Calculate(12); //Assert Assert.Equal(144, result); } } } |
As the tests were written before the code, they helped to make sure that the first implementation of Fibonacci in the video worked correctly. Then, when the second implementation of Fibonacci was written, two of the tests failed:
This is the huge bonus of having tests, because after checking it, the code was amended within minutes – adding an explicit solution for the first two cases of Fibonacci:
1 2 3 4 |
if (position == 1 || position == 2) { return 1; } |