150 likes | 517 Views
Unit Testing. unit testing is a procedure used to validate that individual units of source code are working properly A unit is the smallest testable part of an application In procedural programming a unit is a function, procedure, subroutine, etc.
E N D
Unit Testing • unit testing is a procedure used to validate that individual units of source code are working properly • A unit is the smallest testable part of an application • In procedural programming a unit is a function, procedure, subroutine, etc. • In object-oriented programming, a unit is a method • The goal is to show that the individual parts are correct
Unit Testing with xUnit • Test fixture : a class that contains one or more test methods • Test method : a method that executes a specific test • Test runner : an application that finds and executes test methods on test fixtures • Assertion : a Boolean expression that describes what must be true when some action has been executed
Class to be unit tested public class Account // Class Name { private double balance = 0.0; // Member field public Account(double b) // Constructor { balance = b; } public double Balance // Getter (Accessor) { get { return balance; } } public void Withdraw(double amount) // Member Method { if (balance >= amount) balance -= amount; } public void Deposit(double amount) // Member Method { // TO DO } }
Test Fixture [TestClass()] public class AccountTest { ... [TestMethod()] public void WithdrawTestWithSufficientFunds() { Account acct = new Account(100.0); acct.Withdraw(50.00); Assert.AreEqual(50.0, acct.Balance); } [TestMethod()] public void WithdrawTestWithInsufficientFunds() { Account acct = new Account(100.0); acct.Withdraw(150.00); Assert.AreEqual(100.0, acct.Balance); }
Test-Driven Development • Never write a single line of code unless you have a failing automated test • Refactor to eliminate duplication
Red/Green/Refactor • Write the test code • Compile the test code(It should fail because you haven’t implemented anything yet.) • Implement just enough to compile. • Run the test and see it fail. • Implement just enough to make the test pass. • Run the test and see it pass. • Refactor for clarity and to eliminate duplication. • Repeat from the top.