John Smith
John Smith

Reputation: 6207

Phpunit, one test - one method?

Is it a must that one test must cover one method? For example:

class Testme()
{
    public function testMe ($a)
    {
        if ($a == 1)
        {
            throw new Exception ('YAY');
        }
        else
        {
            return true;
        }
    }
}

maybe not a "real" question though. It could be tested with:

/**
 * @expectedException Exception
 */
public function test1()
{
    new Testme()->testMe (1)
}

public function test2()
{
    $this->assertTrue (new Testme()->testMe (2));
}

but it can be put to one method (in this case its a bit harder to test the exception). What is the good way? One method must be in one test method, or is it OK to test a method in even 4 standalone test method?

Upvotes: 3

Views: 233

Answers (1)

Schleis
Schleis

Reputation: 43790

Rather than thinking about tests/method of your class, you should consider it as one test per expected behavior of the class. In your example, you have two different things that should happen

  1. if the parameter is one, throw an exception
  2. return true for other values

So you would need the two tests because there are two different things are supposed to happen.

Your tests help specify what it is that your code is supposed to DO, not what your code is supposed to look like. A method may result in different things happening depending on the parameters undo which it is run.

Upvotes: 3

Related Questions