An example of testability-driven development
Example of a shopping cart
Public Class Cart
{
Public Logger logger = New Logger ();
PublicList <product> productlist;
Public Cart ()
{
Productlist = New List <product> ();
} Public int gettotalcount ()
{
Return this. productlist. count;
} Public Void Add (product)
{
// Note log
Logger. Log ( String . Format ( " Added a product " ));
// A large segment of Logic
Console. writeline ( "Judge whether repeated " );
Console. writeline ( "Determine whether the product ID is correct " );
Productlist. Add (product );
}
}
Logger was like this at the beginning.
Public Class Logger
{
// Insert Database
Public Void Log ( String Message)
{
Console. writeline ( String . Format ( " Insert Database: {0} " , Message ));
}
}
TestCode,... Do I need to write a database for testing? I just want to test the logic of the shopping cart...
[Testmethod ()]
Public Void Addtest ()
{
Cart cart = New Cart ();
// Todo: Initialize to an appropriate value
Product = New Product ();
Cart. Add (product );
Assert. areequal < Int > ( 1 , Cart. gettotalcount ());
}
Start testability refactoring
Public Interface Ilog
{
Void Log ( String Message );
}
Public ClassLogger: ilog
{
//Insert Database
Public VoidLog (StringMessage)
{
Console. writeline (String. Format ("Insert Database: {0}", Message ));
}
}
Test code modification
Public Ilog logger;
PublicCart (ilog logger)
{
Productlist =NewList <product> ();
This. Logger = logger;
}
Public Class Memlog: ilog
{
Public Void Log ( String Message)
{
Console. writeline ( " Just remember the memory " );
}
}
[Testmethod ()]
Public VoidAddtest ()
{
Cart cart =NewCart (NewMemlog (); product Product =NewProduct ();
Cart. Add (product );
Assert. areequal <Int> (1, Cart. gettotalcount ());
}
this operation is performed in the memory instead of accessing the database. For the purpose of testability, we reconstruct the database and use constructor injection, mock object, and other methods, decoupling external dependencies