I'm a newbie in programming (so don't be too harsh) and our instructors are pushing us to develop using TDD since the beginning.
I'm doing a small program that picks a random name. One of my tests attempts to test that the same name is not picked twice, but the test doesn't always pass.
This is the function that randomly picks someone. What I chose the shift method() because it REMOVES the first element of an array.
public function random($coders) {
$coders = ['Paul', 'John', 'Brad'];
shuffle($coders);
$pickedCoder = array_shift($coders);
return $pickedCoder;
}
This is the test:
public function testCoderNotKilledTwice()
{
$coders = ['Paul', 'John', 'Brad'];
$killer = new Killer();
$deadCoder1 = $killer->random($coders);
$deadCoder2 = $killer->random($coders);
$this->assertNotEquals($deadCoder1, $deadCoder2);
}
What am I doing wrong?
"I choosed the shift method() because it REMOVES the first element of an array."
...sure but then $coders = ['Paul', 'John', 'Brad'];
inside your "random()" function just re-creates the array anyway each time with the original values. The changes you've made using shift() aren't preserved in between calls to "random()". And even if you removed that, every time you call $killer->random($coders);
it passes the original array in as well.
You would need to define $coders
as a (private) property at the class level, so its value persists in between calls to the random() function. There's no need to declare $coders within the random() function, nor to pass a copy into the function as an argument.
Something like this:
class Killer {
private $coders = ['Paul', 'John', 'Brad'];
public function random() {
shuffle($this->coders);
$pickedCoder = array_shift($this->coders);
return $pickedCoder;
}
}
And then:
public function testCoderNotKilledTwice()
{
$killer = new Killer();
$deadCoder1 = $killer->random();
$deadCoder2 = $killer->random();
$this->assertNotEquals($deadCoder1, $deadCoder2);
}
Bear in mind of course that you might also want to account for the scenario where you no longer have enough items left in the array to return a value. I don't know how many times you're expecting to be able to run the random() function successfully.