Reputation:
I have a small method which return true or false if a timestamp is a weekend day i.e. saturday or sunday.
Now i am very new to unit testing and i am trying to write a unit test for this.
In my test case, how would i proceed:
Here is my inital thinking.
1. Pick any 1 week from the past and then...
1.1. Get a timestamp for all 5 week days (mon through fri) and pass each timestamp to the function being tested. If they all return false then proceed...
1.2 Get the timestamp for both weekend days and pass each to function being tested. If they both return true then we know the function is correct.
or
2 Simply pick 1 weekday from the past and 1 weekend day from the past and test with only those 2 dates
Am i correct in either of these approaches or is there a better way to test this?
Upvotes: 2
Views: 686
Reputation: 36532
This calls for a data provider or two. PHPUnit will first call the data provider to get an array containing the data sets it will pass to the test where each data set is an array of parameters to pass to the test method. Next it executes the test once per data set. Here each data set will be a simple date string along with the name of the day for the error message.
/**
* @dataProvider weekdays
*/
function testDetectsWeekdays($date, $day) {
self::assertTrue($fixture->isWeekday($date), $day);
}
/**
* @dataProvider weekends
*/
function testDetectsWeekends($date, $day) {
self::assertFalse($fixture->isWeekday($date), $day);
}
function weekdays() {
return array(
array('2012-08-20', 'Monday'),
array('2012-08-21', 'Tuesday'),
array('2012-08-22', 'Wednesday'),
array('2012-08-23', 'Thursday'),
array('2012-08-24', 'Friday'),
);
}
function weekends() {
return array(
array('2012-08-25', 'Saturday'),
array('2012-08-26', 'Sunday'),
);
}
As for the dates to test, you will need to think about any corner cases that might arise given your class. Will leap years affect it? Time zones? It depends on the implementation which is part of unit (white box) testing.
Upvotes: 2
Reputation: 328584
If you put several checks into a single test, you will have the problem that you won't know what some of the checks might return when one of the first ones fails. Say the method fails for day #3. Would it work for day #4? This information could be very useful when trying to find the bug.
My approach is to test all values at once. It works like this:
This way, you can see with a single glance for which dates the method fails.
The other option is to write 8 tests and have each test check a single date.
Tip: Tests like this tend to fail when timezones are introduced. Create more tests which use timestamps that are close to midnight and play with the timezome. Is the result still correct?
Upvotes: 1