Archive | Testing RSS feed for this section

Testing email component in CakePHP 2.1.x

14 Oct

Are you still sending yourself emails when you run test cases? I was.

Being relatively new to TDD this took a while to get my head around, but using “mocks” has proven to be really useful.

I’ll focus on the CakeEmail class in CakePHP 2.1.x as this proved most useful when writing test cases for Copify (we send _alot_ of emails!)

Here’s what one of our model methods looked like originally (before we had a test case).

When we started writing tests for other areas of the application which used this method, it fired an email.

To get round this, we had to mock the CakeEmail component. This also means you can test it is doing what it is supposed to be.

So to test this, we first need to make a change to the method itself:

Now, we can mock the CakeEmail class and test to ensure each part of our model method does what it should:

The worlds most basic example of Unit Testing

12 Oct

1. In my head, I know what I want a method to do before I even write it, so I write a test that will pass if the code (that I write in step 2) works. In this case it is a basic method in one of my Models.

My fixture has 5 jobs already, I expect the next job to have an ID of 6 and a cost of 18.00

 

2. To make the test pass, here is my REAL method that I add to my model….

 

This just saves the job, the passed arg is an array like the one in the test (or at least I hope it is!)

 

3. Now lets run the test…

 

My test passes - my code does what I had in my head (saves a job)

 

4. Some other guy on the team changes some code…

 

Someone else on the team makes some weird change, probably high on meow

 

5. Looking at the change, it won’t work. The passed arg IS an array, so it will throw an exception. But my original test will catch the fact that this method does not work anymore, otherwise this bug could have gone unnoticed.

 

Before going live with these changes we would run all the tests, in this case, the app doesn't work!

 

From the failed test, you can even see which line of code is failing.

Obviously if you have not written a test for something it can not fail, so being thorough and making sure any bit of functionality has been tested its easy to catch problems and fix bugs.

And if you’re using Git, you can even see who broke the project. Then take it in turns to beat the developer around the head with a blunt instrument.

The worlds most basic summary

Ask yourself “The code I am about to write, what should it do/not do” – then write a test that covers any conceivable eventualities FIRST. Then write the real code to make the test pass.