C # Test

Source: Internet
Author: User

1. Generating unit tests from the code being tested

1.1 Creating a C # Console program named Addunittext

1.2 and then practice it with a small piece of code that's very simple.

1  class program2     int Add (9}ten}    

1.3 Then use the following steps to create a unit test

(1) In the Add method body, select Create Unit test in the right-click menu and create a basic framework for the unit test code for this method

(2) After clicking OK, the system automatically generates unit test code, as shown below

 1Namespace AddText2 {3/// <summary>4///This is the Programtest test class designed to5///Includes all Programtest unit tests6///</summary>7 [TestClass ()]8PublicClass Programtest9 {101112Private TestContext testcontextinstance;1314/// <summary>15///Gets or sets the test context that the context provides16///Information about the current test run and its capabilities.17///</summary>18Public TestContext TestContext19 {20Get21 {22return testcontextinstance;23}24Set25 {Testcontextinstance =Value27}28}2930#RegionAdditional test features31// 32//When writing tests, you can also use the following features:33//34//Use ClassInitialize to run code before running the first Test in a class35//[ClassInitialize ()]36//public static void Myclassinitialize (TestContext TestContext)37//{38//}39//40//Use ClassCleanup to run code after all tests in the class are run41//[ClassCleanup ()]42//public static void Myclasscleanup ()43//{44//}45//46//Use TestInitialize to run code before running each test47//[TestInitialize ()]48//public void Mytestinitialize ()49//{50//}51//52//Use TestCleanup to run code after each test run53//[TestCleanup ()]54//public void Mytestcleanup ()55//{56//}57//58#Endregion596061/// <summary>62///Test of ADD63///</summary>[TestMethod ()]65Publicvoid Addtest ()66 {Program target =New program ();// TODO: initialized to the appropriate value 68 int a = 0; span class= "comment" >// TODO: Initialize to the appropriate value 69 int b = Span class= "number" >0; // TODO: Initialize to appropriate value 70 int expected = 0; // TODO: Initialize to appropriate value 71 int Actual 72 actual = target. Add (A, b); 73 assert.areequal (expected, actual); 74 assert.inconclusive ( "75} 76} 77}              

(3) ProgramTest.cs code file details

[TestMethod ()]: illustrates that the following code is a test case

Int a = O; TODO: Initialize to the appropriate value

int b = 0; TODO: Initialize to the appropriate value

These two sentences are the input parameters of the measured function, and we need to modify its value, which is where we enter the test case.

Double expected = 0; TODO: Initialize to the appropriate value

Double actual;

These two words are easy to understand, the previous sentence is to define the expected value and initialize it, after the sentence is to define the actual values. Default

Assert.AreEqual (expected, actual);

Assert can be understood here as an assertion: unit testing in VSTS is based on assertion testing.

The default code in Assert.Inconclusive indicates that this is an unverified unit test. It can be commented out in the actual program.

(4) You can also create your own unit test project in a C # project, and then write a test method

The basic method of unit testing is to call the function of the code under test, enter the function's parameter value, get the return result, and then compare with the expected test results, if the equivalence is considered to pass the test, otherwise it is considered that the test does not pass.

1, the use of the Assert class

Assert.Inconclusive () indicates a test that is not validated;

Assert.AreEqual () tests whether the specified values are equal, and if so, the test passes;

Aresame () is used to verify that the specified two object variables are pointing to the same object, otherwise it is considered an error

Arenotsame () is used to verify that the specified two object variables are pointing to different objects, otherwise it is considered an error

Assert.istrue () tests if the specified condition is true, and if true, the test passes;

Assert.isfalse () tests whether the specified condition is false and if false, the test passes;

Assert.isnull () tests whether the specified object is a null reference, and if it is empty, the test passes;

Assert.isnotnull () tests whether the specified object is non-null, and if not NULL, the test passes;

2, the use of Collectionassert class

Used to verify whether the collection of objects satisfies the criteria

Use of the Stringassert class

Used to compare strings.

Stringassert.contains

Stringassert.matches

Stringassert.tartwith

3. Use of additional test properties

The default is commented out, as long as we cancel the comment can be used. The addition of this feature is largely to increase the flexibility of testing. The specific attributes are:

[ClassInitialize ()] Run code before running the first test of a class

[ClassCleanup ()] Run code after all tests in the class are run

[TestInitialize ()] Run the code before running each test

[TestCleanup ()] Run code after each test run

4. Test Unit NUnit Declaration

1.AreEqual

Assert.AreEqual (expected,actual[,string message])

Determine whether the result is equal to the expected

The results of the report are as follows:

ASSERT.AREEQIA; (expected,actual,tolerance[,string message])

2.IsNull

Assert.isnull (Object [, String message])
Assert.isnotnull (Object [, String message])

Whether the declared object belongs to an empty

3.AreSame

Assert.aresame (expected, actual [, String message])

Whether the declaration is of the same type

4.IsTrue

Assert.istrue (bool condition [, String message])

Determine if the return condition is true

5.Fail

Assert.fail ([string message])

The test failed immediately.

2.1 This is the test code:

Find maximum value in list[]: int largest (int list[], int length);

The first implementation code is as follows:

int largest (int list[], int length)

{

int I,max;

for (i = 0; i < (length–1); i + +)

{

if (List[i] > Max)

{max=list[i];}

}

return Max;

}

2.2 Writing the program:

 1Staticvoid Main (String[] args)2 {3int[] List =Newint[3];//Declare an array of length 3 to hold 3 numbers of entries4int Max =0;//Save Maximum Value5for (int i =0; i < list.length; i++)//Loop array6 {7 Console.WriteLine ( " Please enter" + (i + 1) +  "8 list[i] = int. Parse (Console.ReadLine ()); // loop saves the entered numbers to the array 9 if (List [i] > Max) // determine if the current number is greater than the maximum 10 { 11 Max = List[i]; // assign the maximum value to Max12}13}14 Console.WriteLine ( " output maximum 15 console.readline ()                  

2.3 During this test, it was found that the program could not be tested effectively, so the method was re-written

 1Namespace Munittext2 {3PublicClass LIU4 {5/// <summary>6///Put the maximum value returned in the list7/// </summary>8/// <param name= "List" > a column of integers</param>9/// <returns> maximum returns the given list </returns> 10 public static int Largest (int[] list) 11 {12  int i, max = Int32.MaxValue; 13 for (i = 0; i < list. Length-1; i++) 14 {15 if (list [i] > Max) 16 {17 max = List[i]; }19}20 return max; }22}23}          

2.4 Creating a unit Test

Tested multiple sets of data

Give a list of numbers [7,8,9]. This method returns 9. This is a very logical test case.

The test idea is given below.

[7,8,9]->9

[8,9,7]->9

[9,7,8]->9

What happens when you have the biggest number of repetitions?

[7,9,8,9]->9

Because there is only an int type, there is no objects type, so you may not be related to what type 9 returns.

So what will it be when there are only 1 numbers?

[1]->1

And what happens when there are negative numbers:

[ -9,-8,-7]->-7

Can be very simple to see-7 ratio-9 large.

2.5 Writing test methods

First: Call using Nunit.framework via globally assembly Cath;

The NUnit framework provides the functionality of the unit tests we need.

Next, we will define a class: Each class contains a comment for the test Case State property. Must be declared as common, it must have a common, no arguments, and constructors.

Finally, the test class contains a single test method with test properties.

 1 using Nunit.framework;23 [Testfixture]45PublicClass testsimple{67 [Test]89Publicvoid LargestOf3 () {10 11 assert.areequal (9,cmp.largest ( new int[]{8,9, 7})); 12 13 assert.areequal (100,cmp.largest (new int[]{100,4, 25})); 14 15 assert.areequal (64,cmp.largest (new int[]{1,64,38 })); 16 17}18 19}     

C # Test

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.