Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘tdd’

TDD – Red Green Refactor Example

Posted by JP on April 7, 2011

 

In this tutorial I would like to explain TDD (Test Driven Development) with the common Red Green Refactor example.

A note on TDD

TDD (Test Driven Development) is a software development process in which the unit test will be written first and after that the original code. In TDD, the design and development of the code is through the unit tests.

In the traditional unit tests, the unit test is written after the original code is written. This is only for long term maintainability. But in TDD the unit test is written first and code evolved through it.

Red Green Refactor

Red Green Refactor is an interesting concept in TDD. The stages are given below:

Red – First a failing unit test is created and it results in red status

Green – We will modify the associated code to just make the unit test pass – resulting in green status

Refactor – Once the test is passing we can refactor the code so that the original implementation is done.

Example: In the following example, I would like to take you through the Red Green Refactor steps. Here we are trying to create a Stack data structure which is already in the library of .Net. We can call our stack as MyStack which operates on string and have Push method.

Step 1: Create a red test project

Create a new test project and name it TDDExample.clip_image002

Step 2: Rename the default UnitTest1.cs to MyStackTest.cs

After renaming the file name just add the following unit test.
[TestMethod]

public void MyStack_Push_Test()

{

MyStack myStack = new MyStack();

bool result = myStack.Push(“abcd”);

Assert.AreEqual(true, result);

}

Please note that first we written the unit test.. till now the original MyStack class is not created.

So place the cursor over MyStack and use Ctrl+. (to Generate Class for us). Repeat the same for Push() method to generate the default method. So now the new class will look like:

class MyStack

{

internal bool Push(string p)

{

throw new NotImplementedException();

}

}

Step 3: Run the unit test and get Red

Run the unit test and you can see the test will fail.

clip_image004

Step 4: Modify the method just enough to make it Green

In this step we are just trying to make the unit test pass. We are returning true without adding the implementation inside the method. So the new method will look like:

internal bool Push(string p)

{

return true;

}

Running the test again, we can see the test passes.

clip_image006

Step 5: Refactor

Although the test is passing now, the actual implementation is not right. Now we need to add the right code in our Push() method. This will be the Refactor step of Red Green Refactor style and the unit test should be passing again.

Our actual implementation would be storing the string to an internal list. The final class would look like:

class MyStack

{

private IList<string> _list = new List<string>();

public bool Push(string str)

{

_list.Add(str);

return true;

}

}

Running the unit test will be green again.

clip_image006[1]

Conclusion

In this tutorial we were trying to create a small example of TDD involving Red Green Refactor style.

Advertisements

Posted in C# | Tagged: , , , , | Leave a Comment »

TDD :: TypeMock :: Reference

Posted by JP on November 3, 2010

Test Driven Development (TDD)

TDD confines to be a good agile methodology.  It will give the long term advantage of maintainability to the code that will give confidence while refactoring.  I believe if properly used there is no much time cost incurred in using TDD, because I a big fan of TDD .

Advantages of TDD

Although it might incur some investment to do TDD in the long run it is definitely advantage especially in product development.  If properly written it should cover all the user code in the application thus making sure changes can be carried with confidence and manageable.  In the long run it will save time and effort multiple times and speeds up the productivity.  Thanks to the creators of TDD.

Mocking

Mocking of code is required while implementing TDD.  There are multiple scenarios we encounter for mocking.

  • When a method is calling a User Interface element
  • When a method is calling a Web Service
  • When a method is calling another method in same class
  • When a method is calling another method in different class

I will show some TDD scenarios that many times we encounter.  It is generally true that whenever the method is going out of its boundary we should mock that.

Note: All the tests are based on TypeMock which is a licensed software.  You need to refer to TypeMock.dll and TypeMock.ArrangeActAssert.dll

Example1: Simple TDD

public class User

{

    public bool IsUserLicensed()

    {

        DialogResult result = MessageBox.Show("Have License?", "Prompt", MessageBoxButtons.YesNo);

 

        if (result == DialogResult.Yes)

            return true;

        else

            return false;

    }

}

The Test method with mocking would look like:

[TestMethod()]

public void Test_User_HasLicense()

{

    User target = new User();

    Isolate.WhenCalled(() => MessageBox.Show(string.Empty)).WillReturn(DialogResult.Yes);

 

    bool result = target.HasLicense();

 

    Assert.AreEqual(true, result);

}

Example2: Testing Method which is calling another Private/Public method

In the previous example MessageBox.Show() was the call violating the scope of method IsUserLicensed().  So we mocked it and it was easier as the MessageBox class was accessible from the test method.

But things won’t be the same.  You might be needed to mock private methods too.  In this case we run into a problem like the method would be not accessible outside the class.

There are two ways of solution for this:

1) Create Private Accessor through Visual Studio, specify the method name as it is

2) Pass the method name as string in mocking

We can try with the second way – passing method name as string

public string GetCitizenship() // Public methods

{

    string citizenship = GetCitizenshipFromDb();

 

    return citizenship;

}

 

private string GetCitizenshipFromDb() // Private Method, we have to mock this method

{

    return "USA";

}

The mocking code for the above would look like:

[TestMethod()]

public void GetCitizenshipTest()

{

    User user = new User();

 

    Isolate.NonPublic.WhenCalled(user, "GetCitizenshipFromDb").WillReturn("USA");

 

    string result = user.GetCitizenship();

 

    Assert.AreEqual("USA", result);

}

 Example3: Mocking a property which do not have setter

The source code will look like:

public bool IsGetterOnlyPropertyValid()

{

    return this.IHaveOnlyGetter == "ValidText";

}

 

private string _iHaveOnlyGetter;

 

public string IHaveOnlyGetter

{

    get { return _iHaveOnlyGetter; }

    // set; – No Setter here

}

From the above IsGetterOnlyPropertyValid()we can see that inorder to return true, the property IHaveOnlyGetter should be “ValidText”.  We cannot set the property from the test method as there is no setter for the property.

The solution would be a different style as given below.

[TestMethod()]

public void IsGetterOnlyPropertyValidTest()

{

    User target = new User();

 

    Isolate.WhenCalled(() => target.IHaveOnlyGetter).WillReturn("ValidText");

 

    bool result = target.IsGetterOnlyPropertyValid();

 

    Assert.AreEqual(true, result);

}

Posted in C# | Tagged: , , | Leave a Comment »