Introduction to Unit Testing Unit testing – testing methods/classes of the program • Test suite is composed of several tests • Test suite should cover all the statements • Tests calls Assert functions What is the Assert Class • One Assert per test – Short circuit – Write simple and concise tests • Checks if different conditions are true Assert Functions • Assert::IsFalse(…) - 3 Basic Overloads -Assert::IsFalse( bool condition); -Assert::IsFalse( bool condition, string message ); -Assert::IsFalse( bool condition, string message, object[] parms ); • One Assert per test – Short circuit – Simple and concise tests Assert Functions AreEqual(int actual, int expected) AreEqual(double actual, double expected) AreEqual(float actual, float expected) AreEqual(decimal actual, decimal expected) AreEqual(object actual, object expected) AreSame (object actual, object expected) Assert Functions IsTrue( bool condition) IsFalse( bool condition) IsNull( object obj) IsNotNull( object obj) Fail() Ignore() Tools available • • • • NUnit WinUnit Visual Studio 2005 Team Edition Visual Studio 2008 Professional Edition Exercise – Use Unit testing in Visual Studio 2008 Create a new test project • Create a new solution and project • Add name • Click OK Add subject class • Download from blackboard the files: – Grade.cpp – Grade.h • Save and add the files in your project • Some configuration properties need to be changed – See next 2 slides Configuring…Project->Properties (Alt+F7) Configuring – more… Configuring…Done! • Build the project • Run the test cases – Test->Run->All Tests in Solution Writing tests • Write a test for setScore(double) method void setScore(double newscore){ if ((0<=newscore)&&(newscore<=100)){ score = newscore; } } • What if newscore = 100 [TestMethod] void TestMethod1() { Grade *g = new Grade(); g->setScore(100); Assert::AreEqual(100.0, g->getScore()); }; • What if newscore = -1 • What if newscore = 101 Exercises • Complete the exercises from the file: Unit Testing Tutorial.doc Warning • Sometimes configuring larger projects to include testing is not trivial – Testing in Notepad++ and WinMerge - not yet • Other unit testing tools are easier to configure – JUnit – testing Java programs – They follow the same principles