unit testing in wordpress

32
Unit Testing in WordPress WordSesh 3

Upload: barry-kooij

Post on 16-Jul-2015

108 views

Category:

Technology


0 download

TRANSCRIPT

Unit Testing in WordPress

WordSesh 3

Manual Testing

Time consuming

Error-prone

Single point of knowledge

Unit Testing

Time saving

Infallible

Knowledge in code

“A unit test is an automated piece of code that invokes a unit of work in the system and then

checks a single assumption about the behavior of that unit of work.”

Write code before tests

Write tests before code

PHPUnit

CLI tool that runs unit tests & reports their results.

Created by Sebastian Bergmann

Easy to install

Unit Tests Requirements

Each test should be able to run on its own (isolated)

Easy to read

Quick to execute

Self explaining function names

Unit Tests Requirements

Test classes should inherit from WP_UnitTestCase (which inherits from PHPUnit_Framework_TestCase)

Test functions should start w/ test (test_my_test_name)

–William C. Wake

“This test case fits a pattern I call ‘Arrange, Act, Assert’: it sets up data, calls a method

under test, and then verifies that it worked as expected.”

Arrange Act Assert

Easy to

- Read- Follow- Understand - Maintain

Arrange

Arrange all necessary preconditions and inputs.

Act

Act on the object or method under test.

Assert

Assert that the expected results have occurred.

Assertion

assertEqual() assertTrue()assertNotNull()assertContains()assertGreaterThan()

https://phpunit.de/manual/3.7/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.assertions

function test_get_single_role_by_user_query() { // Arrange $this->factory->user->create_many( 2, array( 'role' => 'subscriber' ) ); // Act $u_query = new WP_User_Query( array( 'role' => 'subscriber' ) ); // Assert $this->assertEquals( 2, count( $u_query->get_results() ) );}

function test_get_single_role_by_user_query() { // Arrange $this->factory->user->create_many( 2, array( 'role' => 'subscriber' ) ); // Act $u_query = new WP_User_Query( array( 'role' => 'subscriber' ) ); // Assert $this->assertEquals( 2, count( $u_query->get_results() ) ); }

function test_get_single_role_by_user_query() { // Arrange $this->factory->user->create_many( 2, array( 'role' => 'subscriber' ) ); // Act $u_query = new WP_User_Query( array( 'role' => 'subscriber' ) ); // Assert $this->assertEquals( 2, count( $u_query->get_results() ) ); }

function test_get_single_role_by_user_query() { // Arrange $this->factory->user->create_many( 2, array( 'role' => 'subscriber' ) ); // Act $u_query = new WP_User_Query( array( 'role' => 'subscriber' ) ); // Assert $this->assertEquals( 2, count( $u_query->get_results() ) );}

Tools

Barry Kooij

@CageNL

barrykooij.com