CPSC225/Notes/Unit Testing(Bach)

Unit Test is a procedure that is used to validate that an individual module or a unit of source code is working properly. A unit here can be a class, a function or a procedure. The test case can written using mock data or test harnesses (collection of data for testing). In practice, the test code is usually written before actual code is written. How do we test code that we have not written anything? That is because the test code will define how the code will be later on.

Benefits of Unit Test
Easier Code Refactoring: allow for code change in the later state of development and ensure that these changes do not break earlier code. The procedure for unit test is that each function or class should have a test case so that when the programmers change code, they will just run the test case to make sure the new code does not break anything.

Better Integration: by testing each unit of the code first then test the whole source code, unit testing allows for better integration testing of the whole source code.

Better documentation of code: other programmers can look at the test code and see what the code is supposed to do rather than having to read the whole code.

Application of unit test
Test driven development: a concept of Extreme Programming (XP). Before writing any code, the developer writes the test code for that particular unit of code first (the test code must expose the requirement or defect of the code). Then the developer writes the code that just satisfies the particular test case and other previous test.

Unit Test Framework
JUnit: Junit is a Unit Test Framework for Java. As decribed for Unit Test, developers use JUnit to write the test code then use JUnit test runner to see how well the code satisfies the requirement. It also supports integration test (for testing how well pieces of code putting together). public class HelloWorld { 	 @Test public void testMultiplication {  	  // Testing if 3*2=6: assertEquals ("Multiplication", 6, 3*2); } } phpUnit: a Unit Test Framework for PHP public function testNewArrayIsEmpty {       // Create the Array fixture. $fixture = array; // Assert that the size of the Array fixture is 0. $this->assertEquals(0, sizeof($fixture)); }