Original article: unit test using Visual Studio
I. Suggestions on using Visual Studio for unit testing
1. write unit tests first (in my opinion, it should be the interface first, if any)-> test failure-> with minimal changes (that is, write the actual code) make the test pass (but in vs2012 it is no longer possible to generate the test project directly through the existing project. I think this function should be retained. Microsoft is always like this, forcing users to adapt to their products, but have to adapt );
2. Do not append the function (CODE) due to unit test, that is, the logic is not affected by unit test;
3. Changed the logic of the Code (add, delete, modify), and the unit test should be run in time;
4. Declare attribute -- testcategory ("classification or feature name") in the test method ");
5. Add the fakes assembly in the unit test project to separate external dependencies (such as database access and configuration information retrieval );
6. initialize the members and other information in the unit test class. You can add methods and declare attribute [testinitialize] (the method must be public );
II. The following uses vs2012 as an example to illustrate how to perform unit testing in Visual Studio.
1. Right-click solution to bring up the context menu)
Select Add-new project. In the template, select Visual C #-test-unit test project.
2. Obtain the template.
3. Add the code to be tested in the test method (testmethod1 is the default testmethod1 here, which is generally changed to the method name to be tested + test ).
For example, to add the xmlserializationtest class, the Code is as follows:
C # code Replication
[Testclass] public class xmlserializationtest {private xmlserialization serialization; [testinitialize] public void inittest () {This. serialization = new xmlserialization (@ "F: \ usermodel. seri ");} [testmethod] public void testwritexml () {usermodel user = new usermodel (); bool flag = serialization. writexml <usermodel> (User); assert. istrue (FLAG); assert. isfalse (serialization. writexml <usermodel> (null);} [testmethod] public void testreadxml () {usermodel user = new usermodel (); User. loginname = "AA"; serialization. writexml <usermodel> (User); usermodel model = serialization. readxml <usermodel> (); assert. isnotnull (model); assert. areequal (user. loginname, model. loginname); // The path does not exist. null usermodel modelnull = serialization should be returned. readxml <usermodel> (@ "F: \ notexists. seri "); assert. isnull (modelnull );}}
4. After writing the test code, you can click test-run-alltests in the top menu to perform the test.
After the test is completed. The result list is displayed below. The red color indicates the testcase that fails. To debug it, right-click the red testcase and select debug selected tests. After modification, you can also right-click the testcase you want to re-test and select Run selected tests.
Use Visual Studio for unit testing