How to Test PHP/Laravel BackEnd

Just a Random Illustration. Photo by Caspar Camille Rubin on Unsplash

Configuration

You can read a lot more details in: https://laravel.com/docs/5.8/testing, Laravel has a really good documentation, and I recommend it.

docker-compose stop mysqltest
sudo rm -Rf ~/.laradock/data/mysqltest
docker-compose up — force-recreate — build -d mysqltest
docker-compose up -d nginx
docker-compose exec workspace bash
<env name=”DB_HOST” value=”mysqltest”/>
#DB_CONNECTION=mysql
#DB_HOST=mysql
DB_HOST=mysqltest
DB_HOST=#IP
DB_PORT=3306 #the standard port
### MySQLTest ################################################
mysqltest:
build:
context: ./mysql
args:
- MYSQL_VERSION=${MYSQL_VERSION}
environment:
- MYSQL_DATABASE=${MYSQL_DATABASE}
- MYSQL_USER=${MYSQL_USER}
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
- TZ=${WORKSPACE_TIMEZONE}
volumes:
- ${DATA_PATH_HOST}/mysqltest:/var/lib/mysql
- ${MYSQL_ENTRYPOINT_INITDB}:/docker-entrypoint-initdb.d
networks:
- backend

Unit Tests

Models and Validate the Relationships

public function testOwner()
{
$model = myModel::first();
$this->assertInstanceOf(User::class, $model->owner);
}
public function testCreateComment()
{
$answer = new Comment();
$data = [
‘commentary’ => “content of this comment”,
‘post_id’ => 1,
‘comment_id’ => “2”
];
$this->assertInstanceOf(Comment::class, $answer>create($data));
}
public function testTotalLikes()
{
$model = myModel::first();
$this->assertInternalType(“int”, $model->totalLikes());
}

Feature Tests

Users

$user = User::find(id);
$response->assertStatus(200);
parent::assertPaginatorJsonStructure($response);
$myThing_id = $response->json()[‘message’];
$this->assertInternalType(‘int’, $myThing_id);
/**
* Describing Endpoint
* @depends Endpoint_Dependency
* @return void
*/
public function testMyEndpoint($param)
{
[$dependency_one,$dependency_two] = $param;
$user = User::find(id);
$uri = ‘/’ . $dependency_one . ‘/something/’ . $dependency_two . ‘/anotherthing/’ . $stuff_id;
$data = [php_array_thatll_be_converted_to_json_later];
$response = $this->http_method($uri, $data, parent::getApiAuthHeaders($user));
$response->assertStatus(200);
$response->AnyAssertionYouWish;
}

Dependencies and Simulating Workflow

Some endpoint depend in a DB change cause by another endpoint, so to simulate a workflow we include in our code the following:

return [$first_dependency,$second_dependency];
/**
* Endpoint Description
* @depends testDependency
* @return void
*/
public function testEndpointWithDependency($params)
{
[$first_dependency,$second_dependency] = $params;
…etc…

Considerations

Huge Thanks to Clickideia, Educational Company which this tests belongs to.

Just a brazillian fullstack dev, who loves applying IT into education