开发者

Whats the right place for testhelper-classes? (phpunit/best practise)

I want to test my application with PHPUnit. So I have my application-classes and a second tree with test-classes as usual. Now I need for some test a kind of Dummy/Mock-Objects and I want to know where I should place them. Is it a different usecase and it should be place in comm开发者_运维问答on lib folder or what is to prefer?


In the cases where I don't use mock objects but instead create a throw-away subclass for the test case, I name the class with the test case's prefix and place it in the same file after the test case itself.

The test case prefix avoids any chance that the class's name will clash with any real classes, and placing the code in the same file makes it easy to work with the test. If you find that you need to create multiple subclasses for one test case, this is probably a signal that your class does too much.

class MyClassTest extends PHPUnit_Framework_TestCase
{
    function setUp() {
        $this->fixture = new MyClassTest_DoesNothing;
    }
}

class MyClassTest_DoesNothing extends MyClass
{
    ...
}


I like to mirror the file structure of the project I am working on.

/project
  app/
  app/models/BankAccount.php
  tests/
    suite/
      app
      app/models/BankAcountTest.php
    mocks
      app/
      app/models/BankAccountMock.php

I find doing it this way keeps everything organized. I will put small Mocks or stubs in the Test Case File if I don't intend to reuse them. As was stated in the other comments, most Mocks can be generated by PHPUnit, but sometimes it is easier just to roll your own.


There is no suggested place for where to place hardcoded stubs or mocks. I tend to add a folder _files whenever I feel the need for specific external resources in the same folder as the test that needs those. But that just me.

However, PHPUnit has a built-in mocking framework, so in general you dont need to hardcode your Stubs and/or Mocks. See the

  • chapter on Test Doubles in the PHPUnit Manual.

Example 10.2: Stubbing a method call to return a fixed value

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMock('SomeClass');

        // Configure the stub.
        $stub->expects($this->any())
             ->method('doSomething')
             ->will($this->returnValue('foo'));

        // Calling $stub->doSomething() will now return
        // 'foo'.
        $this->assertEquals('foo', $stub->doSomething());
    }
}

An alternative to PHPUnit's Mocking framework would be Pádraic Brady's Mockery, which is inspired by Ruby's flexmock and Java's Mockito

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜