We learned the common attributes of nunit and their usage methods. Let's start with simple exercises.
Let's write a simple bubble sort for actual use.
Add a Bubble sorting method to the calculate class.
public int [] BubbleSort (int [] array){ for (int i = 0; i array.Length -1 ; i++) { for (int j = 0 ; j array.Length- i -1 ; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } return array;}
Add the test method to calculatetest as follows.
If we only want to run this test method here, we can use the ignore explicit category and other attributes we learned earlier.
[Test]public void TestBubbleSort(){ int[] array = {-1,4,2,8,54}; int[] result = cal.BubbleSort(array); int[] expect = {-1,2,4,8,54}; Assert.AreEqual(expect, result);}
Run nunit.
Add a test method to calculatetest
[Test]public void TestBubbleSort2(){ int[] array = null; int[] result = cal.BubbleSort(array);}
Run nunit
Obviously, we have not considered that the input parameter is null. In this case, complete bubblesort:
Public int [] bubblesort (INT [] array) {If (array = NULL) {console. error. writeline ("the array parameter cannot be null"); return New int [] {};}for (INT I = 0; I array. length-1; I ++) {for (Int J = 0; j array. length-I-1; j ++) {If (array [J]> array [J + 1]) {int temp = array [J]; array [J] = array [J + 1]; array [J + 1] = temp ;}} return array ;}
We added a non-null judgment for the parameter for the bubblesort method. If the input parameter is null, a prompt "parameter array cannot be null" is displayed.
We have verified the case where the parameter is an int [] array and the parameter is null. But there is another case: When the array is empty.
[Test]public void TestBubbleSort3(){ int[] array = {}; int[] result = cal.BubbleSort(array); int[] expect = { }; Assert.AreEqual(expect, result);}
Run nunit,
It's really nice to see this green environment. Haha
The final Bubble Sorting Code is as follows: added a judgment on whether to change the position:
Public int [] bubblesort (INT [] array) {If (array = NULL) {console. error. writeline ("the array parameter cannot be null"); return New int [] {};}for (INT I = 0; I array. length-1; I ++) {bool iswap = false; For (Int J = 0; j array. length-I-1; j ++) {If (array [J]> array [J + 1]) {int temp = array [J]; array [J] = array [J + 1]; array [J + 1] = temp; iswap = true ;}} if (! Iswap) {return array ;}