Writing Test Cases with PHPUnit

Preview:

DESCRIPTION

Writing Test Cases with PHPUnit

Citation preview

Unit Test Cases

Shouvik Chatterjee

Senior Product Engineer, Kayako

@tweetshouvik

Is It Important?

Yes! Yes!

Yes!Yes!

Yes!

Yes! Yes!

Yes!Yes!

Yes!

Yes!Yes!

Yes!Yes!

Yes!Yes!

Yes!

Yes!

Spot the bug! Pastie.org

PHPUnit

What is PHPUnit?

PHPUnit by Sebastian Bergmann is an advanced unit testing framework for PHP.

Frequently used Methods

1. assertEquals()

2. assertInstanceOf()

3. setUp() & tearDown()

4. setUpBeforeClass() & tearDownAfterClass()

5. @dataProvider

6. @expectedException & @expectedExceptionMessage

assertEquals()

assertEquals(mixed $expected, mixed $actual[, string $message = ''])

Reports an error identified by $message if the two variables $expected and $actual are not equal.

Pastie.org

assertInstanceOf()

assertInstanceOf($expected, $actual[, $message = ''])

Reports an error identified by $message if $actual is not an instance of $expected.

Pastie.org

setUp() & tearDown()

setUp() method is called before every test case, which means that this method can be called few times per one test class.

Similarly, tearDown() method is called after every test case.

Pastie.org

setUpBeforeClass() & tearDownAfterClass()

setUpBeforeClass() method is executed only once per class, and even before object is constructed, and that is the reason why it is marked as static public function.

Similarly, tearDownAfterClass() method is called after all tests in class finish, and after last tearDown() method is called.

Pastie.org

@dataProvider()

A test method can accept arbitrary arguments. These

arguments are to be provided by a data provider method.

The data provider method to be used is specified using the

@dataProvider annotation.

Pastie.org

@expectedException & @expectedExceptionMessage

The @expectedException annotation is used to test

whether an exception is thrown inside the tested code.

The @expectedExceptionMessage annotation lets you

make an assertion on the error message of an exception.

Pastie.org

Rules of Thumb

Don’t write test cases for

the sake of writing.

Be descriptive when writing test cases.

public function testCreateReturnsTrue() { … }

public function testCaseOne() { … }

Make use of the PHPUnit’s built-in methods.

$this->assertTrue($isValidStatus);

$this->assertEquals(true, $isValidStatus);

Try splitting up your test cases as much as possible for the sake of

readability.// Case 1 public function testCreateException() { … }

// Case 2public function testCreateSuccess() { … }

// Case3public function testCreateReturnsFalse() { … }

Try to keep your test cases

independent.

Pastie.org

Pastie.org

Questions?

Thank You