Thursday, June 17, 2010

Testable function

Make sure the public function returns some value or reference or status of the execution. So that the function can be unit tested.

C# example- Below is a non testable function.
//should not allow value less than 1 and greater than 100
public void SetAge(int iAge)
{
    if (iAge >= 1 && iAge <= 100)
    {
        m_iAge = iAge;
    }
}
The above function, if called gets executed but the caller would not be sure about the result of execution, so the caller has to get the age again and check if it was set correctly.
C# example- Below is a testable function.
//should not allow value less than 1 and greater than 100
public bool SetAge(int iAge)
{
    bool blnStatus = false;
    if (iAge >= 1 && iAge <= 100)
    {
        m_iAge = iAge;
        blnStatus = true;
    }
    return blnStatus;
}

Note: Minimize coupling (dependency between classes and modules) as much as possible, which could highly improve the testability of the entire module.

Rule: Write testable function.

No comments: