Question

im new to unittesting and trying to follow TDD.

I my CardStackTest, there is number of tests, like these...

public function testGetTopStackThrowsExceptionIfFirstArgumentNotInt()
public function testGetTopStackReturnsNullIfNoCardsAvailable()
public function testGetTopStackReturnsInstanceOfCardStack()
public function testGetTopStackRemovesAmountOfCardsFromStack()
public function testGetTopStackReturnsRestOfCardsIfNumberHigherThanCardsAvailable()

Now... these are all working and all is fine and gladly accept hints for better test method naming.

My question is. In my mind, i have already invisioned a getBottomStack method. And i know it will need exactly the same testing as my getTopStack method. Maybe i would add one extra test beyound this.

My first idea was to make private method like testReturnsInstanceOfCardStack and then make the public test point to the private.

But should i write each test in same fashion, or is there a way to dry this up, maybe making some reusable tests?

Was it helpful?

Solution

If you see that you start to get code-duplication within the test-case you can start to refactor the code of the test-case as well.

However, take care that you do a refactoring only when all tests are green (pass). This rule does not only apply to the code-base but also to the test-base.

For example, you can move duplicate code into a private method that you then call in the public testXyz()-Method.

Here is an example given of a private helper function in a test-case, the scenario is different, but it should help to illustrate, from the answer to "PHPUnit Testing version of assertIsA":

private function assertNumber($actual, $message = "Is a number")  {
    $isScalar = is_scalar($actual);
    $isNumber = $isScalar && (is_int($actual) || is_float($actual));
    $this->assertTrue($isNumber, $message);
}

Another way to make a re-usable test is with a data-provider, however that is more for test-data. If for example multiple test methods require the same test-data both can share one data-provider.

Hope this helps for some general guidance. Try out yourself and don't forget to put all your code and tests under version control and you commit often.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top