Hello World of Rhino Mocks

by percent20 1/16/2008 1:19:00 PM

Mock Objects are something that I hear more and more and more and more about as I continue my path into the TDD world, and even from some not in the TDD world.  They are a wonderful tool for helping you to create code for tests that hasn't been implemented yet. Or to help test your data access code without having to run to the database every time you run a test.  Before we go much further lets get a more "formal" definition of Mock Objects.  For that lets visit Wikipedia:

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to test the behavior of a car during an accident.

To use Rhino Mocks first you need to download Rhino Mocks then unzip it somewhere on your hard drive.  Then in your projects just go to add references in the solution explorer then the browse tab then find the assembly where you unzipped it and tada you are read to start.

So let me introduce you to basically what the application is I wrote to mess with mock objects.

Getting Started

First, let me tell you I don't completely understand what is going on with Rhino Mocks and "how" it works.  At this point I know just enough to start "using" mock objects and that is what I want to pass on to you today.  I assembled this code together from around 20 different tutorials so please do not look at this as best practices.  So in typical TDD fashion lets start with test. (I am including the top portion of the file so you can see what I have above the actual test)

Test

HelloWorld Test

Firstly, don't forget to add references to NUnit and your Rhino Mocks assemblies.  You will also need to setup all the appropriate attributes for your tests.  If you do not know how to do this please visit my Part 2 of TDD for Beginners.

MockRepository mock = new MockRepository();

This is the object you create initially that will store all of your mock objects that you are going to be using. (That is what I gather from what it does and the name)

IWorld world = mock.CreateMock<IWorld>();

As best I understand this code we are creating an instance of IWorld object as if it was an object that inherited from IWorld.

using (mock.Record())

From my understanding this basically will run and in this block of code is where we load our mock object with what the objects will do.  Like we are going to basically say what the world object is going to do.

Expect.Call(world.GetWorld()).Return("World");

With this we just told our mock object that it can expect us to call the GetWorld method that is in the world object and it will return the string "World".  So now when we use this object later it will have a method implemented that will return a string.

using (mock.Playback())

In this section of code is where we start USING our mock objects to write our test.

Person p = new Person()
string saying = p.SayHello(world);

Here we create an instance of our person class that is going to call its method SayHello and pass it that mock world object we create above as if it a real and fully created world object.

Assert.AreEqual("Hello World", saying);

This is just a normal assertion that we do for our test.

Making the test Compile

At this point if you were to try and compile it wouldn't so we will implement the code to make it compile.  Lets start with the IWorld interface.

IWorld

That is all you need for the IWorld interface.  And that is all you will need TOTAL for the whole example for IWorld.  Next is the Person Class.

Person Class 

The thing to notice about this piece of code is that for our parameter we are using IWorld as the type and not World since we don't have a world object yet, but we know that we are going to implement it later.  Later the world object will inherit from the IWorld interface so the method will know what to do.

So now it should compile and the test should fail. This is good.

Making the test Pass

All that we need to do to make the test pass is to add change line of code now.

SayHello Method

With this code it takes the object that it was passed and uses it as if it where a regular a real object, but it was created as a mock object in our test.  The great thing is that since we created the mock object and gave it its mock functionality we can implement code to USE that functionality even though it really doesn't exist YET.

To drive home the point on my own and test further I went ahead and created a test using a real world object and a world object.  It worked like a charm.  Those are below.

World Object:

CropperCapture[31]

Real Object Test

World Object Test

Wrap-Up

I hoped that this helped to give you an understanding of mock objects and how to use Rhino Mocks to use mock objects.  I am starting to like mock objects the more I read about them mostly because I can not worry about the database code itself until last, as I don't enjoy it, and can start to work on the application itself and create a layer that is calling mock objects to retrieve data.  Then later turn those mock objects into a real data access layer and I am set to go.

Please feel free to leave any comments or criticisms the more the merrier.

RhinoMocks_1.zip (7.42 kb)

kick it on DotNetKicks.com

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | TDD | Tutorials

TDD for Beginners pt4 - Unit Tests

by percent20 1/14/2008 4:34:00 PM

Part 1: TDD Test Driven Development for Beginners pt1
Part 2: TDD for Beginners pt2 - Pig Latin
Part 3: TDD for Beginners pt3 - The Application
Part 4: TDD for Beginners pt4 - Unit Tests

Recap

I just want to remind everyone of the goals of this series.  It is not to be ALL TDD all the time, but a series on what is TDD and how to start using it on an existing project. Part  1, 2, and 3 are all lead ups to doing this.  Part 1 described what TDD is.  Part 2 described how to do TDD.  Finally, Part 3 setup an existing application that we are going to have as our "Existing" project.  Again, since a lot of people want to start using TDD right away they don't always get the option to start a new project so they need to be able to integrate TDD into an existing application.  My purpose is to give a taste of that with this series while describing some of the basics of TDD and over all concepts and goals of TDD.  This is not an all inclusive how to do TDD and would be irresponsible of me if I said it was as I am still learning TDD myself.

Getting Started

Unfortunately, we can't start doing TDD from the very beginning of a project all the time, would be nice.  We often times come into a project and have to put up with existing code that is usually not easily testable which is pretty unfortunate and can leave you with an icky feeling at times.  This part is going to be about how to implement tests on existing code.

What are we going to test?

I am glad that you asked that question.  Since there are many ways to test things we are only going to test our Business Logic Layer we presented in the Part 3 "TDD for Beginners pt 3 - The Application". If you have not read it I highly recommend you do.  We are going to leave the testing of our Data Access Layer to our final part in the series.

So, right now we want to get our code tested at least a little bit before we start adding features so lets write some tests for our 4 methods. 

  • RetrieveContacts()
  • AddContact()
  • UpdateContact()
  • DeleteContact()

Our Solution

There are many ways to set up your projects to do testing.  In this project I simply made a sub folder called tests and am throwing my tests in there, and they will be built into the application.

Solution Explorer 

Lets take a moment and do some planning based on what this code is doing.

First, we are going to be testing the BusinessLogicLayer Class so that means that we want to use the BLL in ever method that we are going to write our test with.  Since the BLL only does data manipulation in a static way we don't really "need" to create an instance of it in each method.  NUnit provides a SetUp attribute that allows you to do "stuff" before any of the tests are ran such as create instances of objects or populate variables to be used in the tests across your current test fixture.

 

SetUp Attribute

At the top of this code we see our class declaration and the class is going to be a test fixture that will have tests in it (explained in Part 2).

BusinessLogicLayer bl;

Here we are setting up the object that will be used by the tests to access and do stuff with our data.

[SetUp]
public void SetUp()

This is a declaration that the SetUp method is going to be called first because of the SetUp attribute.  How, I look at it is the SetUp method with the SetUp attribute is the constructor of the test fixture it is called first before anything. (the method can be named anything it just makes sense to me to name it setup)

bl = new BusinessLogicLayer("Contacts.xml");

This is just creating an instance of BusinessLogicLayer object and adding that instance reference to the bl object.  Pretty straight forward. Like assigning a variable a value.

Before we move on I want to point out that up until this time the code that we had written in the past with no tests had not been implemented while writing the code so basically it lead to having to try and write all the code at once implement it in some way and hope it all works.  By writing tests we can write a test write a bit of code and then test and tweak until the code works.  At least to me this makes me feel safer about my code actually working because I know, pretty much, as I am writing the code it works. So now lets move on.

Lets talk strategy of testing our data interaction.  One way to test is to try and do stuff on existing data, but that can be dangerous because what if we shouldn't touch the data that exists? We still need to test right? This leads us to the option of what about adding our own data that we know everything about and testing against it then removing it (I did not think of this on my own it came from the book Test Driven Development in Microsoft .NET).  Doing it that way makes sense because then that limits me from accidentally deleting something I shouldn't delete.

Now, with that strategy in mind you should realize now that we are going to be adding data in every test.  So something easy we can do is to create a Contact object in the setup since that is the data we are going to be passing around anyway.

SetUp Method

If you notice the only thing we did was to create a new Contact object and populate it.  Pretty straight forward stuff.  So now lets move onto some the tests.  I want to say here that I may switch back and forth between explaining lines of code and/or chunks of code.  So just be prepared for that as you go along.

RetrieveContacts()

Code:

CropperCapture[13] 

Test:

RetrieveContacts Test

I am not going to explain the naming convention of the test that is done in Part 2 of this series needless to say you kind of get the idea of what the purpose of the test is by the name of it.  Again this part assumes you have read at least part 2 and 3.

List<Contact> l = bll.RetrieveContacts();

This line is fairly simple it is getting a list of all contacts that are in the xml file.

Assert.IsNotEmpty(l);

I like this assertion it you can check to make sure if the method was successful with out having to do much at all just make sure the collection isn't empty.

AddContact()

Code:

CropperCapture[14]

Test:

AddContact Test

bll.AddContact(contact);
List<Contact> l = bll.RetrieveContacts();

Right of the bat we are adding our contact to our xml file and then going ahead and retrieving all the contacts out of the xml file.  So lets now check and see if it is even in there.

bool foundWhatINeed = false;

We are setting up this bool as kind of a switch that if the contact information is in collection then this switch will be true all all will be right in the land of oz.  If not the bad monkeys will come down and take us away and the switch will be false.

Contact theContact = null;

The reason we are setting this up is because if the contact does exist we still have something to do with the contact, like at least remove it.  To do this we need information about it so a good way to do is to get an instance of that contact.

foreach (Contact c in l)
{
    if(c.Name == contact.Name && c.Email == contact.Email)
    {
        theContact = c;
        foundWhatINeed = true;
    }
}

So, we are basically just iterating through all of our contacts, and since we know the specific information about our contact we just compare the name an email address of our hopefully completely unique name and e-mail address.  If it is in the collection we flip our switch and assign the instance of the object to theContact variable.

if (!foundWhatINeed)
        Assert.Fail("Contact was not in list");

Here is what is done with our little on off switch.  If our contact wasn't able to be found we force failure of the test with Assert.Fail and leave a message of why.  Please, be more descriptive than what I was when you do this.

bll.DeleteContact(theContact.sGuid);

And finally since we no longer need that data in the xml file because we added and checked that it was there we can go ahead and delete it from the xml file.

UpdateContact()

Code:

CropperCapture[15]

Test:

UpdateContact Test

I am not going to explain this code line by line as it does the exact same thing as the last 2 tests just a bit more involved.  I am going to do a bullet point description.

  • Add our initial contact and retrieve all contacts from the list
  • Setup our initial switch and object for getting the contact
  • Checks to see if contact is there if so then adds the contact to theContact object if contact is there test fails right there
  • Change a basic bit of information the name and assign the guid of the object to our original object that we are just updating
  • Update the contact
  • Next we just run through our check again to make sure it was all updated if not the test fails
  • then we delete the contact from the xml file.

DeleteContact()

Code:

DeleteContact()

Test:

DeleteContact Test

Same principle applies here as above you know what is going on so I am going to bullet point the explanation, but this is going to be even shorter since it is basically the same code.

  • Add the contact
  • Make sure it was added
  • Delete the contact
  • Make sure it was deleted

Wrap-Up

So in wrapping up this part of our TDD series I want to stress that these are in no way excellent tests that should be reproduced for all time because they are so great.  In fact they can use improvement and can be done different and better ways.  I just wanted to show you how to write some basic Unit Tests for existing code in an existing application.  I hope that this gives you an idea of A how you can write tests for code.  Stay tuned for our next part where we start using TDD on this application to add a new feature.

Final Notes

Here is a bit of homework please I am adding the files for you to download and play with please take a look and see if you can simplify the tests even more or see if you can write them a different way.  Please, play around a bit to see what you can do.

Also note that there are 2 BusinessLogicLayerFixture classes both have the same tests the one with 2 at the end is a simplified version of the other.  I wanted to include both to show that you should and can try to clean up your test to make them look and work better.  I left some more stuff to be cleaned up and move around in the Fixture2 hoping you would give it a shot. Please download and play.

TDDContactManagementApplication_UnitTests.zip (9.11 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

.NET | TDD | Tutorials

TDD for Beginners pt3 - The Application

by percent20 1/9/2008 5:36:00 PM

Part 1: TDD Test Driven Development for Beginners pt1
Part 2: TDD for Beginners pt2 - Pig Latin
Part 3: TDD for Beginners pt3 - The Application
Part 4: TDD for Beginners pt4 - Unit Tests

In Part 1 we went over the conceptual ideas of how TDD works.  In Part 2 we went over a basic how to do TDD doing string manipulation and going through each of the steps.  Here is a quick _rough_ recap of what we are going to do for the rest of the series

Part 4: Explain how to create tests for existing non-tested code
Part 5: Use TDD to add a search feature
Part 6: Refactor code to make things work a bit better
Part 7: How to use Mock Objects

NOTE: I started out this series using .NET 2.0, but have recently started using .NET 3.5 and using Visual Studio 2008. Since, this will be the first release of the project it will be in .NET 3.5 using VS 2008.

Getting Started

The application that we are going to be using is a console application that is a contact management system.  Something very basic that will allow you to view, add, update, and delete contacts that you know.  It will save out all the contact information into an XML file so that we can keep the data as long as we need.  I will start by saying that the UI portion of the code is ugly and pretty simple.  A lot of Console.WriteLine("");'s. With that being said I won't explain that portion of the code as it is fairly simple and quite repetitive.  First, I want to show you the solution explorer and I'll go over it a bit with you.

Solution Explorer

  • Tests - Just ignore this folder for now we will go into that on the next part.
  • BusinessLogicLayer.cs - this is our source code that our GUI will access to interact with data.
  • Contact.cs - Like was explained in Part 1 of our XML Series this is our Contact Class that acts as a data type for our application.
  • Contacts.xml - We store all of our data in this file.
  • DataAccess.cs - This holds all of our code to access data in our Contacts.xml file.
  • Program.cs - The main method is in this file along with the code for the GUI

The only things we are not going to discuss here is the Tests folder and the Program.cs file. First, though lets start with the DataAccess.cs and Contact.cs file.

DataAccess.cs

For a good understanding of this code please refer to the xml series I have previously posted as it is the exact same code.  The only change is the Contact.cs file and I will address that when it comes, but it is only code changed to be C# 3.0 compliant, it does the same thing.

Part 1: Write to XML File Using C#
Part 2: Reading Data from XML File Using C#
Part 3: Delete Data from XML File Using C#

Contact.cs

This class again is our custom class that we use as a data type as explained in Part 1 of the XML Series "Write to XML File Using C#".  There is only a minor change to the code to update it to C# 3.0 specs as you can see below.

CropperCapture[3]

BusinessLogicLayer.cs

First, I guess we should explain a bit about what a Business Logic Layer (BLL) is a bit.  There can be 3 main parts to your application to have good separation of concerns.  First you have your Data Access Layer, this layer is used strictly to do your CRUD only. Second layer is your Business Logic Layer, which is used to handle any data manipulation; like adding information to each piece of data and it doesn't necessarily need to be in the database.  In the BLL you could even use that point to combine pieces of information or format the data in a specific order.  Third you have your presentation layer which is basically where you present your stuff to the user for them to see and use.

Now, what we have gone through a brief explanation lets take a look at some code.

BusinessLogicLayer.cs

We will skip the first few lines as I am sure you can guess what they do so lets jump to line 9 and we'll go method by method or line by line.  I'll try to keep the explanations fairly straight forward and simple. (The below assumes you have gone through the the XML Series)

DataAcces da;

We are creating a variable of type DataAccess so we can have a global DataAccess object to the BusinessLogicLayer class so that we don't have to create an instance of the DataAccess object for every method call.

public BusinessLogicLayer(string xmlFile)
{
    da = new DataAccess(xmlFile);
}

This is the constructor for our class we are creating passing in the name of the xml file to use and then creating an instance of the DataAccess object with the name of the xml file. 

public List<Contact> RetrieveContacts()
{
    return da.RetrieveContacts();
}

With this we are just getting a collection of all the contacts in the xml file from our DataAccess object that access the xml file.

public void AddContact(Contact c)
{
    da.AddContact(c);
}

This simply is a layer of abstraction to the DataAccess class that adds the contact to the xml file.

public void UpdateContact(Contact c)
{
    da.DeleteContact(c.sGuid);
    da.AddContact(c);
}

Here is a bad way to update a contacts information, but it does work.  (I did this on purpose to explain something in a later part)

public void DeleteContact(string s)
{
    da.DeleteContact(s);
}

And on this one we delete the data from the XML file using a provided Guid that comes from our presentation layer.

At this point some people may be asking "why" would you not just use the DataAccess class directly.  Well I am glad you asked because that is an important thing to know.  One of the big reasons is, what if later we want to change this all to a database instead of an XML file?  Well with this program that really would be a problem, but if it was a huge application we could run into some problems.  Adding this Business Logic Layer adds the advantage of allowing you to just rewrite the Data Access Layer to use a database and all that is required for you to do is use the same method calls in the DAL.  Imagine being able to use this application later on with a DB if we only had to re-write one part of 3 parts of the code and it would be a guarantee to work then why wouldn't you want to do this, not to mention it adds to better readability.

Contacts.xml

This is our data store and is explained in the xml series part 1 Write to XML File Using C#

Program.cs

Finally we have the file that actually runs all the code I will just provide a download of the file for you to look at as it is long and ugly looking.

Program.cs (3.75 kb)

Wrap-Up

This is a nice little gap filler part that introduces you to the application and lets you download and play with.  I also wanted to inform you as to what was coming and get out of the way some preliminary conceptual "what is going on" with the application.  Please feel free to download the code below and play with it.  Please stay tuned for Part 4 of our TDD series.

TDDContactManagementApplication.zip (6.45 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

.NET | TDD | Tutorials

TDD for Beginners pt2 - Pig Latin

by percent20 12/5/2007 4:48:00 PM

Part 1: TDD Test Driven Development for Beginners pt1
Part 2: TDD for Beginners pt2 - Pig Latin
Part 3: TDD for Beginners pt3 - The Application
Part 4: TDD for Beginners pt4 - Unit Tests

I like to do "Real World Coding" and "Real World Contexts" when doing tutorials, if I can. Someone suggested that most people that want to learn and do TDD usually want to start using it with an existing project, and I should go about the series in that way. I liked that idea, but it presented a simple problem of teaching the very basics of TDD. My solution is this part 2. I am going to walk you through doing a _VERY_ basic Pig Latin converter, and how to use TDD to accomplish writing it. Then the rest of the series is going to be how to incorporate tests into an existing project, and a couple parts on adding new features using TDD.

Download NUnit
Before you can do TDD you need to get something to run your tests. I personally use
NUnit, but there are other options available.
Download
( Get the MSI for the latest version using .NET 2.0 Library )
Documentation

Next you need to Install it just run the installer. Just go through the normal next next next process.

How to configure Visual Studio to do Tests
This is pretty straight forward process and is a project by project basis. When you install NUnit it will add several NUnit assemblies to the GAC and when you start a new project that you are going to write tests for (which should be most now), you need to add new refernce, in the solution explorer, and choose NUnit.Framework assembly. Next you add the following line to your using statements.

using NUnit.Framework;

Once that is done you are pretty much set and ready to start writing tests.

Test Driven Development

Now that we have the preliminary stuff out of the way we can start to concentrate on what is important. Learning Test Driven Development. Sorry for the long post you are about to endure.

What we are going to write is a Converter class that allows us to convert words to another language. In the case of our example we are going write a class to be able to convert words to pig-latin (as long as the word doesn't start witha vowel). By writing it as a convter class it will make the code easier to use, implement, test, and extend.

TDD Process
There is a basic process you run through when doing Test Driven Development. I wrote about it in another post, but will re-list it here as it is very important and is the core to TDD.

  1. Write the Test Code
  2. Compile the Test Code (It should fail since you haven't implemented anything yet)
  3. Implement Just enough code to Compile
  4. Run the Test to see it fail
  5. Implement just enough to make it pass
  6. Run test to see it pass
  7. Refactor for clarity and eliminate duplication
  8. Rince and Repeat (repeat from the top)

I am going to walk you through each of these steps and explain them as I go.

Write the Test Code

First we need to create our test class file. So add a class file to a new console project (if you want following along) and name it ConverterFixture. The name means that this is a test file that will be testing the converter class.

Test For Converter Class

The above code is what we refer to as writing the test code first. Lets walk through each line.

[TestFixture]
This is the attribute we set in C# to let NUnit know this class containts tests. It is a Nike thing "Just do it" at the top of your test classes. The class also must be public for NUnit to find and use it.
public class ConvertFixture
This is the name of the class that is going to containt all of our tests for our Converter class.
[Test]
This is the attribute we set in C# to tell NUnit this is an actual test that will be run. All the code in this method below is used to ultimately run a test.
public void ShouldConvertWordToPiglatin()
In order for the method to be a test it needs to be public, void, non-static, and take no parameters. Our method meets all those requirements. The naming might seem odd, but the purpose is so that you can easily understand the purpose of what "should" happen by the end of this test (Look up Behavior Driven Development). This may be obvious by our method test, but when you get into more complex code then tests can become exponentially longer with the purpose being lost. Though nameing is up to you this is what I do.
Converter c = new Converter();
Creates a new instance of the Converter object.
string word = c.ToPigLatin("hello");
From this code we are converting a word "hello" to pig latin using the instance of the converter object from above and assigning to a string object. Or we are converting hello to pig latin.
Assert.AreEqual("ellohay", word);

This is the bread and butter, kind of, of tests. Assertions are how you actually test things in TDD and using Assert object is how you do it in NUnit. There are actually quite a few Assertions you can make, but the one we have here is Assert.AreEqual which compares what the output "Should be" to what it actually is. I suggest when you get this far take a look through intellisense at all that are available to you to use.

Now what we have is a test for our converter object that we haven't made yet.


Compile the Test Code

If you are following along and doing TDD the correct way when you hit compile you will get a big fat ERROR and it won't compile. Congrats that is exactly what it is supposed to do. If it does compile something is wrong.

Implement Just enough code to Compile

At this point we are ready to start writing code for our program. We will write just enough code for our program to compile. The reason behind this is so that you don't write unecessary code and the more code you try to write to pre-implement/pre-solve problems can lead to problems later. Writing just enough code to compile can keep you in check so that you don't write too much code. Here is the code that is just enough to compile the program.

- In this code you can see we created the class Converter.
- Created a method called ToPigLatin() with a return type of string and takes a string parameter.
- It then returns the string s.

Now try to compile. It should compile with 0 errors.

Run the Test to see it fail

Next is to actually run the test. To do that here are the steps I follow from finding and opening NUnit to hitting run. Once you open the assembly in NUnit all you need to do is just hit run from then on after each compile.

  1. Start
  2. All Programs
  3. NUnit 2.4.3
  4. Click NUnit GUI (.NET 2.0)
  5. File
  6. Open Project...
  7. Find assembly (which was in below folder)
  8. Location of Assembly
  9. Select Assembly
  10. Click Open
  11. Click Run

At this point it the test should fail

Test 1 Fails on First Run

 

Implement just enough to make it pass

No we are ready to add the functionality to make that stinking test pass so we can feel good about our code working.

The code above is the code needed to make the test pass. I will run through the code mostly line by line after the declaration of the method.

char[] theArray = s.ToCharArray
Here we are taking the string and spliting up each individual character into an array to so we can manipulate it better.
string final = "";
We are setting the variable final to a nothieng string because are going to run through a loop and add characters to it.
the whole for loop
This is basically going through the array for the word and starting at the second character and assigning it to the variable final. So basically it is taking "hello" and turning it into "ello".
return final + theArray[0] + "ay";
Here we are taking ello adding h to the end and then appending "ay" to it. The final looks like ellohay. We then take that and return it so the test can check if it was done right.

Run test to see it pass

Now you should be able to hit the bug run button in NUnit once you compile the program and get everything all Green.

Feels good doesn't it.

Refactor for clarity and eliminate duplication

In this case we really don't have anything that we need to refactor so we can do the next step.

 
Rince and Repeat
(repeat from the top)

If we had more to do then we start over from the top on the next method/functionality that we want to write. Remember though not to write to much functionality at once.

 

Wrap-up

Now that we have gone through all the steps i'll post up the final code and the code that implements the converter class we just wrote. Then the application that runs it.

ConverterFixture.cs

Converter.cs 

Implementation inside the main method

Program.cs

It actually running

 

Final Thoughts

As you can see Test Driven Development can be very effective in making sure that your code does work. What is great about TDD is that you can spend a while coding on a project and because you have tests later when you do some refactoring to make things prettier and work better you know if and where EVERYTHING is broken. Also TDD allows you to start almost anywhere in your application that you want so if you want to start in the business logic layer, lets say, and not in your data access layer you can because there are ways to test without haveing the Data Access Layer implemented, I will show that too later.

There are a lot of benefits and I can only talk about a couple of the benefits right now so as the series progresses I'll talk about more. In the next part, maybe couple of parts , of the series i'll post up the code for our application that doesn't have tests and do a walk through of all the code.

Please, feel free to download the code I have attached play with it maybe add your own language converter to it with some tests. Please give me any feedback you want good bad or indifferent.  

TDDSeries1PigLatin.zip (7.81 kb)

kick it on DotNetKicks.com

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

.NET | TDD | Tutorials

TDD Test Driven Development for Beginners pt1

by percent20 11/29/2007 1:27:00 PM

Part 1: TDD Test Driven Development for Beginners pt1
Part 2: TDD for Beginners pt2 - Pig Latin
Part 3: TDD for Beginners pt3 - The Application
Part 4: TDD for Beginners pt4 - Unit Tests

You know I might not be the most qualified person to talk about TDD. I may not be the best developer in the world with TDD, but I struggled with it for a long time and I want to help others get through the “Basics” with less pain than I went through learning TDD.

First Let's talk a bit about TDD. We are going to hit the basic questions.

Who: Who can do Test Driven Development?

- Anyone. Everyone who programs can do test driven development since it is a type of development. A way to do development.

What: What is Test Driven Development?

- Good question. Test Driven Development is a type of development where you use your code before you write it. Yeah you read that right. You use your code before you write it. What this basically means is that you write a test for a piece of code before you actually write your code. This may seem odd, but once you get the hang of it TDD is quite powerful.

When: When do you use Test Driven Development?

- All the time. Again TDD is a way to develop software so it can be done anywhere on anything for the most part.

Where: Where do you use Test Driven Development?

- Everywhere. If you write code somewhere you can use TDD to help write it.

Why: Why would you use Test Driven Development?

- Ah, the 100 million dollar question. Why would you possibly want to do this. Well the answer is simple. Eventually you are going to need to use your code. At some point your code is going to be implemented and you want to make sure it works. So the best solution is to put forth a little for-thought and pre-implement your code. That way when you write your code you know when it is working.

How: How do you use Test Driven Development?

- Well we will get to that in the next few parts as this is a multi-part series.

Now these are some vague descriptions and answers. I did that on purpose for one key reason to make you think for a few minutes.

Let me just run you through some of my experience with Test Driven Development. At first it was plain hard to figure out what in the world was going on. It didn’t make any sense of why or how you can implement code you haven’t written yet or why you would. It still kind of boggles my mind. However, as I have used TDD more and more I have grown to like it A LOT. In some respects it is like a video game while using NUnit you write a test write enough code to get a compilation run the test hey it fails and is red. Now you plug away at that one piece of code until it is green.

I think the absolute greatest thing about TDD since I have started it and is why I am loving it is because I can completely restructure my code and as long as ever test passes I know my code is good. Also if I do break something I know where it is broken and where to begin to look. Think about it for a second. If you have say 10,000 lines of code and 90% of it has tests and you have to do some major refactoring or redesign you will know what breaks and where immediately instead of having to try and run the program to figure that out.

I just want to make one last point. I am still learning TDD and am still a junior developer. However, I have a passion for coding and passion to help other people not fall victim to learning stuff the hard way and the long way like I had for TDD.

I also suggest reading a post I made before I decided to do this series TDD (Test Driven Development) for beginners and More on TDD "so much code"

Stay tuned for part 2.

Note: as part of full disclosure this is not a new post.  I just changed the date as I started this series then stopped blogging for a while and am wanting to get back to this.  I just feel people should see this before I go into part 2. Just trying to stay honest.

kick it on DotNetKicks.com

Currently rated 3.3 by 4 people

  • Currently 3.25/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Programming | TDD

Documentation Types for Source Code

by percent20 11/1/2007 5:46:00 PM
One thing I frequently run into when coding and reading code is the lack of comments in code and documentation for code, especially in the OSS (open source software) community. As a “beginnermediate” developer I often look to quality code for how I should code, but am frequently disappointed when I see little to no comments and documentation. This is especially frustrating when I want to use a new library or technology. From experience and what I would like to see more developers do I want to write more on documenting code.

As I see it there are 4 types of documentation that all code should have accompanying software.

   1. In code comments
   2. Generated documentation from code
   3. Tutorials
   4. Unit Tests

1) In code comments – comments that usually are short descriptive comments to explain 1 to 2 lines of code max

2) Generated documentation from code – In the .NET world this would be XML Comments which when you do a compile against the code you can extract out all of the xml comments for better documentation of what is going on in the code and view them in your browser. Usually XML Comments are descriptive informative comments about large chunks of code

3) Tutorials – One thing that is needed when creating libraries and programs are tutorials on how to use it. Usually well thought-out tutorials are best, but at least something to tell/show the user what and how to use your product is one of the best forms of documentation you can provide.

4) Unit Tests – As a person that works/talks with Test Driven Development people Unit Tests are a great form of documentation because if you use a good naming convention for your tests you can tell what the test is doing. Also it is a form of a tutorial in that you can see HOW to use pieces of code hopefully many different ways.

So, there is a basic overview of documentation types. I will expand on these with full length posts and addendums as time passes.

p.s. Remember just because I write for “newbs” doesn’t mean that experienced developers can learn
something from “newbs” as they often time forget the simple things.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

.NET | Documentation | Open Source | TDD | Programming

PHP and TDD environment

by percent20 6/22/2007 1:11:00 PM

As many of you know I am taking a dive into doing TDD. Well since I have a side job doing php development I am going to try and do TDD with php using PHPUnit. To do that we need to set up our development environment to even do that.

First, I want to show you to a PHPUnit e-book
http://www.phpunit.de/pocket_guide/index.en.php

Now there is a lot of good information in there, but frankly I find it a pain to figure out what they saying sometimes so I will give kind of excerpts of what to do in more layman’s terms.

Lets get started setting up the environment. Since I am a proponent of portable development, basically I don’t have a server running all the time and I can turn off sql and the web server when I am not using it. I suggest using XAMPPLITE. So here is a bit of how to use and install it.

XAMPPLITE:

  1. Download here.

  2. Uzip to C:\xampplite (my suggestion it just makes it easier)

  3. run xampp-portcheck.exe to see if anything is using the required ports if so turn off the apps

  4. run xampp-control.exe – this gives you a nice gui app in your task bar to start and stop mysql and apache.

  5. all source code for web development goes in the C:\xampplite\htdocs\

You should now have XAMPPLITE installed and ready to go. Our next step is to add the php folder to our path. I’ll tell you how to do it my way, BUT I want to stress if you do it MY way you can hurt your system and it is not my fault.

Add php folder to path (way 1) – note don’t need to do this unless you want to install and use PHPUnit for TDD

  1. open commandline Start->run->cmd

  2. type Path

  3. rightclick topleft corner of command window go to Edit -> select all

  4. repeat step 3 except choose copy

  5. Open notepad Start->run->notepad

  6. Paste

  7. delete everything BUT the folders listed

  8. turn off word wrap

  9. add “;C:\xampplite\php\” to the end of folder without quotes

  10. make sure everything is on one line

  11. go to beginning of line add “path ” without quotes and be sure to include the space

  12. copy that one line with everything on it. Should be LONG.

  13. paste in command line using step 3 with paste instead of select all

  14. hit enter.

Now that should work it is how I usually do it. I’ll give you another “safer” way. Just remember I am not responsible if you mess up your computer.

Add php folder to path (way 2) – This is the safer method I recommend this one to everyone.

  1. Right click my computer

  2. choose properties

  3. advanced tab

  4. Environment Variables button at the bottom

  5. Select Path in System Variables area

  6. hit edit

  7. add “;C:\xampplite\php\” to the end without quotes

  8. ok

  9. ok

  10. ok

  11. now reboot computer

Now that you have the folder added next we need to install PHPUnit. This is much easier. Basically is just to command line commands. Find out more here.

Install PHPUnit

  1. Start->run->cmd

  2. type “pear channel-discover pear.phpunit.de” without quotes

  3. hit enter

  4. type “pear install phpunit/PHPUnit”  without quotes

  5. hit enter

Now you should have PHPUnit installed. 

I just want to kind of sum up what we have done. 

  1. Installed a portable way to start doing php development without installing anything that would be hard to remove.

  2. Added PHP folder to the path so we can install and run PHPUnit

  3. Installed PHPUnit

The greatest part about all this is no extra process are running when you aren’t using them.  Later I will go over actually writing tests with php and using php unit. This was just a lets get started type thing so you can do at least PHP development. Later i’ll come back and go over more of what TDD is and when how and why you want to use it.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

PHP | TDD | Programming

More on TDD "so much code"

by percent20 6/16/2007 1:09:00 PM

As you may know I have been trying to learn Test Driven Development. One thing that has always bugged me is how much code you write just to test something. To me it seems like you should spend most of your time writing your application not writing tests.

Well believe it or not writing a lot of test code is great.  As I am working through examples I have realized the more tests you write the stronger your code is. Reason I say this is because say in 2 years when you come back to your code and add or change something and 20 tests break, that you will probably never notice, you know that hey there is a potential bug.  When you fix that hey you have good code because all your tests pass and you are testing every part of your app not just a small bit of it.

So in the end I realize now that writing a A LOT of test code is a good thing because it leads to a better final product.

Currently rated 4.0 by 2 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

TDD | Programming

TDD (Test Driven Development) for beginners

by percent20 6/13/2007 1:07:00 PM

I have been wanting to learn TDD for a long time now and finally took the plunge and bought a book over it.  It is “Test Driven Development in Microsoft .NET.” I have only started the book, but already I understand TDD a little more than what I did before and most of that has to do with a few steps it laid out quite simply.  It is basically the process you go through when writing your code.

  1. Write the Test Code

  2. Compile the Test code (It should fail since you haven’t implemented anything yet)

  3. Implement just enough to compile

  4. Run the Test to see it fail

  5. Implement just enough to make it pass

  6. Run test to see it pass

  7. Refactor for clarity and eliminate duplication

  8. Repeat from top

For me I understood this, even though it was till hard to figure out, but what I didn’t “get” that was ok to have happen was step 2 which is in bold. It is ok for your compiled test to not compile.  The great thing about TDD is that it is one of those things you can do in almost any language I mean heck you can do TDD with PHP. PHPunit.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

TDD | Programming

Powered by BlogEngine.NET 1.3.0.0
Theme by Mads Kristensen


My Flare

AddThis Feed Button

National Blog Posting Month

Eagle Scout

I'm Test Driven

[Reserved for MVP status I want to earn]

View Buddy Lindsey's profile on LinkedIn

Twitter



Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Sign in