Learning how to test code is one the most valuable things that I have learned. It was not so long ago that I ran into my first big software development challenge at work. I had just spent half a month on developing a new product when i realized that my methods were unreliable and the data structure was not scalable. This was a very scary place to be. Enter RSpec. RSpec is a testing framework for the Ruby Language that is based on the ideas of Behavior Driven Development. In a nutshell the philosophy goes something like this:
- Gather information about the product from the client.
- Turn this information into specifications for the behavior of the code.
- Write modular scenarios describing the conditions for the project.
i.e. an invoice should have customer id
- Observe that your tests fail.
- Write just enough code to get them to pass.
- Enjoy a well documented and optimized solution!
So, When it came time to work on a project for school, (Data Structures and Algorithms) I was determined to not dilly dally around with debugging. I needed to build tests! And so i began searching for a framework that would allow me to be explicit and expressive with my assertions and a product that would require very little effort to get off of the ground. I found two frameworks that met the criteria:
CPPSpecGoogle Test
I chose Google Test for several reasons:
- really good documentation.
- an xCode user base.
- A slick interface to create custom Assertions.
- Death Tests.
LInks:
Google Test on Google Code.
Behaviour Driven
Excellent Video on BDD.
Sample Code:
namespace {
class ListIteratorTest : public testing::Test {
protected:
ListIteratorTest() : iter_one(some_numbers)
{
}
virtual ~ListIteratorTest()
{
}
virtual void SetUp()
{
int array[6] = {5, 3, 9, 2, 4, 6};
for (int i = 0; i <= 5; i++)
{
iter_one.insert_with_order(array[i]);
some_numbers.up_size();
}
}
virtual void TearDown()
{
}
List<int> some_numbers;
ListIterator<int> iter_one;
};
/*
//####################################################
// Description
//
TEST_F(ListIteratorTest, method_does_this)
{
ASSERT_EQ(value, some_method);
ASSERT_TRUE( lhs == rhs);
EXPECT_TRUE(condition);
}
//...................................................
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//####################################################
// Make sure an item is properly removed from a list.
//
TEST_F(ListIteratorTest, remove_takes_away_the_item)
{
ASSERT_TRUE( iter_one.remove(2) == true);
iter_one.start();
ASSERT_EQ(3,iter_one.getEltAtCur());
}
//...................................................
//####################################################
// Delete an item in a list .... if it exists.
// if it is not there, tell her about it.
//
TEST_F(ListIteratorTest, if_no_delete_return_false)
{
ASSERT_TRUE(iter_one.remove(7) == false);
ASSERT_TRUE(iter_one.remove(2) == true);
}
//...................................................
}// end name space
Posted by
Ryan Smith