UNIT TEST Research Report | [<<] [>>]
1. Basic Concept 1) What is unit test? The unit test is the lowest level test activity to be performed during the software development process. In the unit test activity, the software's independent unit will test in the case of isolating other parts of the program. There will be many tests during the programming process, and the unit is only one of them. The unit test does not guarantee that the program is perfect, but in all the tests, the unit test is the first link, which is also the most important part. . Unit testing is a work that is tested by the programmer. Simply said that the unit test is whether the test code writer executes whether or not the expected result is created in terms of its way. 2) What is test driver development (TDD, Test-Driven Development)? Test driver development to test the center of the development process, which requires the test to define product code behavior before writing any code, and the product code written in turn will make the test. Test drive development requirements test can be run automatically, and tests must be run before the code is reconstructed. Its basic practice is as follows: 1. Write a test program. 2. Let the program compile. 3. Run the test program and find that you cannot run. 4. Let the test program can run. 5. Eliminate repeated design and optimize design structure. 2. Why use unit test 1) Reducing the bugs of the program to reduce the number of errors in the software, the method is to have a professional test group, and its job is everything possible to crash. Unfortunately, if you have a test group, even if you are an experienced developer, it will also tend to spend less time to ensure the reliability of the code. Software industry has a saying: "Developers should not test their own code." This is because developers have a good code of their own, and they know how to test the code with the appropriate approach. Although this says make sense, it is very important to ignore the very important point - if the developer does not test your code, how can the code run in the expected way? Simply put, they have nothing to know. Developers write a serious problem that runs normal or only in some cases. They usually only test code can run normally in a few cases, rather than verifying that the code can run normally in all cases. 2) Improve development speed. Generally, everyone will think that unit testing will waste time, this is a misunderstanding. Once the coding is completed, developers always want to integrate software, so they can see the actual system starts to start. This seems to be an obvious progress in the appearance, and the event of the unit test may be seen as an obstacle to the road to this stage, postponed this true interesting of the entire system. Work started. In this development step, the progress in the true sense is replaced by progress on the appearance. The possibility that the system can work is very small, and more cases are full of a wide range of bugs. In practice, such a development step often results in such a result: software can't run. Further results are a large amount of time will cost to track the simple bugs contained in the independent unit. In individual cases, these bugs may be trivial and insignificant, but in general, they will lead to software. Integrate additional work during integration, and cannot be securely run when this system is put into use. In practice, the complete planned unit testing and the energy cost of writing the actual code are substantially the same.
Once these unit tests are completed, many bugs will be corrected, and when confident that their hand has a stable and reliable part, developers can make more efficient system integration. This is a realistic progress, so the unit test under the full plan is a more efficient use of time. The uncontrolled and scattered work of debugging people will only take more time and have achieved few benefits. There are many situations where software errors are found: 1. Developers who have written code for the first time. 2, the developer who tried to run the code found. 3. Discover other developers or testers from the group. 4. As part of the product's large scale test. 5, found by the end user. If the software is found in the first case, the repair error is relatively easy, and the cost is also very low. After the situation is more, the higher the cost of repairing the software error; repairing a software error discovered by the end user may cost 100 or 1000 times cost. Moreover, users usually have the next version to solve the problem since the software error has not been able to continue. If the developer can discover all the software errors during the code, then it is fine. To do this, you must write a test that can run when writing code. There is a very good way to do this. Experience shows that a unit test method that will find a lot of bugs in some stages of software development, and the cost of modifying them is also low. In the later stage of software development, BUG discovery and modification will become more difficult and consume a lot of time and development costs. No matter how often makes a complete regression test, testing the software products as early as possible, and the efficiency and quality will be optimized. In the case of a test-tested unit, the system integration process will greatly simplify. Developers can focus on interaction between units and global functions, rather than falling into units full of BUGs. 3) Make the program code more neat, the optimization program is only the automatic unit test program fails, we will rewrite the code. In the test driver development, we require us to reconstruct the program, through reconstruction, we The structure of the program can be optimized to eliminate potential errors in the program. At the same time, in order to be able to test your own procedures, developers need to be well considered for the design, and the limit programming can start coding without design, but in fact, it is writing code Each time is performed to optimize your design in order to make it easy and through testing. It is actually a very abstract design that is very abstract in the start phase to each method you write. So they will say that the design will naturally appear naturally. 4) The process of writing a unit test code is actually the process of designing a program. When writing a unit test code, we are actually thinking about our procedure based on what results are expected, it is actually the process of programming. Through the reconstruction process, we can optimize these designs. 3. How to make unit tests I have to demonstrate how to write unit tests during application development. Before the demo, we have installed unit test tools such as NUnit or VSNUnit.
There is a user in our program, it corresponds to a userS table in the database, which is as follows: use system; namespace db {public class users {public users ()} private system.string _password; public system.string Password {get {return _Password;} set {_Password = value;}} private System.DateTime _LastLogon; public System.DateTime LastLogon {get {return _LastLogon;} set {_LastLogon = value;}} private System.String _Name; public System .String Name {get {return _Name;} set {_Name = value;}} private System.String _LogonID; public System.String LogonID {get {return _LogonID;} set {_LogonID = value;}} private System.String _EmailAddress; Public system.string emaildress {get {return_emailaddress;} set {_emailaddress = value;}}}}}}}}}} We use another class EntityControl to synchronize the data in this class through the ORM method to synchronize the data in the database, here we only need to know that it has this feature.
using System; using System.Reflection; using System.Data; using System.Data.SqlClient; using NHibernate; using NHibernate.Type; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Tool.hbm2ddl; using System.Collections; namespace DB {/// /// Summary description for UsersControl /// public class EntityControl {private static EntityControl entity;. private static ISessionFactory sessions; private static Configuration cfg; private static dialect dialect; public static EntityControl CreateControl () {if ( entity == null) {buildSessionFactory (); if (entity == null) entity = new EntityControl ();} return entity;} private static void buildSessionFactory () {exportSchema (new string [] { "users.hbm.xml" , "Divartment.hbm.xml", "e MPLOYE.HBM.XML "}, false);} public void addentity {iSession s = sessions.opensession (); itransaction t = s.begintransaction (); try {s.save (entity); t.commit (); Catch (Exception E) {t. rollback (); throw e;} finally {s.close ();}} public void updateentity (object entity, object key) {iSession s = sessions.opensession (); Itransaction t = s.begintransaction (); try {s.Update (entity, key); t.commit ();
} Catch (exception e) {t. rollback (); throw e;} finally {s.close ();}} public void deletentity (object entity) {iSession s = sessions.openSession (); itransaction t = s.begintransaction (); Try {s.delete (entity); t.Commit ();} catch (exception e) {t. rollback (); throw e;} finally {s.close ();}} public object geteTiTies .Type theType, Object ID) {Object Obj; iSession S = sessions.opensesis (); itransaction t = s.begintransaction (); obj = s.load (THETYPE, ID); T.Commit (); s.close );} Public ion iliry {iplic {ilist lst; iSession s = sessions.opensession (); itransaction t = s.begintransaction (); lst = s.find (query); t.commit (); S.Close (); RETUR N Lst;} public ilist getentities (string query) {iist lst; iSession s = sessions.opensesis (); itransaction t = s.begintransaction (); lst = s.find (Query, Value, TYPE ); T.commit (); s.Close (); return Lst;} #Region "Schema DEAL" private static void exportschema (String [] FILES) {exportschema (files, true);} private static void exportschema (String " ] Files, Bool Exportschema) {cfg = new configuration (); for (int i = 0; i {cfg.addresource ("db." Files, assembly.load.
DB "));} if (exportschema) New SchemaExport (CFG) .create (true, true); sessions = cfg.buildsessionFactory (); Diagect = NHibernate.diaalect.diaalect.getdiaalect ();} // /// Drops the schema that was built with the TestCase's Configuration /// private static void DropSchema () {new SchemaExport (cfg) .Drop (true, true);}. private static void ExecuteStatement (string sql) {ExecuteStatement (sql, true) ;} private static void ExecuteStatement (string sql, bool error) {IDbConnection conn = null; IDbTransaction tran = null; try {if (cfg == null) cfg = new Configuration (); NHibernate.Connection.IConnectionProvider prov = NHibernate.Connection .ConnectionProviderFactory.NewConnectionProvider (cfg.properties); conn = prov.getConnection (); TRAN = conn.begintransaction (); idbcommand comm = conn.createCommand (); Comm.commandtext = SQL; Comm.Transaction = Tran; Comm.commandType = CommandType.Text; Comm.ExecutenonQuery (); TRAN.COMMIT ();} catch (exception eXC) {if (TRAN! = null) TRAN. ROLLLBACK ); If (error) throw exc;} finally {if (conn! = Null) conn.close ();}} #ENDREGON}} These two classes provide methods, we can see from the following classs: With the background knowledge above, let's look at how to test the code for these two folding units.
Let's create a class --- UnitTest.cs, in this class, we join the following namespace: use nunit.framework; we add an attribute-testfixture in front of the class name, NUNIT will see this, Process this class as a class test. [TestFixTure] Public Class UnitTest Below we add the following code: private entryControl control; [setup] public void setup () {control = entityControl.createControl ();} [setup] The role is to provide some initialization when the unit test Data, in the latter test method, we can use this data, which seems to be similar to the constructor in our class. Let's see how to test how to increase the user: [TEST] public void addtest () {user = new users (); User.logonid = "1216"; user.name = "xian city1"; user.emailaddress = "tim.wang@grapecity.com1"; control.addentity (user); user2 = (user) control.geeTity (typeof (user.logonid); assert.istrue (u2.name.equals ("xian city1") && u2.emailaddress.equals ("tim.wang@grapecity.com1)); askERT.ISFALSE (U2 .Name.equals ("xian city" && u2.emailaddress.equals ("tim.wang@grapecity.com"));} In the above test method, we first set a new user, then use Addentity to increase it In the data, in order to verify that the data we increase into the database is correct, we take it out according to the primary key by the GeTENTITY method. By comparing if the data we just entered is correct, we conducted two tests twice, one with the correct data, a wrong data, the purpose is to ensure that this test is really a role.