60 lines
1.7 KiB
Markdown
60 lines
1.7 KiB
Markdown
|
---
|
|||
|
title: >
|
|||
|
What's the simplest test to begin with?
|
|||
|
pubDate: 2023-09-07
|
|||
|
permalink: >-
|
|||
|
archive/2023/09/07/what-s-the-simplest-test-to-begin-with
|
|||
|
tags:
|
|||
|
- software-development
|
|||
|
- automated-testing
|
|||
|
- test-driven-development
|
|||
|
- php
|
|||
|
- drupal
|
|||
|
---
|
|||
|
|
|||
|
When giving talks and workshops or coaching on automated testing and test-driven development, some people may not have written tests before and aren't familiar with the structure or know where to begin.
|
|||
|
|
|||
|
In the workshops I ran for DrupalCamp London and DrupalCamp NYC, I wanted to cover this first before writing any implementation code.
|
|||
|
|
|||
|
Where do you put a test class, and what does it contain?
|
|||
|
|
|||
|
How do you run the tests, and how can you make it pass or fail?
|
|||
|
|
|||
|
## What we did
|
|||
|
|
|||
|
To start, we wrote a test for existing functionality within Drupal core - anonymous users can visit the front page.
|
|||
|
|
|||
|
This is the whole test:
|
|||
|
|
|||
|
```php
|
|||
|
<?php
|
|||
|
|
|||
|
namespace Drupal\Tests\my_module\Functional;
|
|||
|
|
|||
|
use Drupal\Tests\BrowserTestBase;
|
|||
|
use Symfony\Component\HttpFoundation\Response;
|
|||
|
|
|||
|
class MyModuleTest extends BrowserTestBase {
|
|||
|
|
|||
|
protected $defaultTheme = 'stark';
|
|||
|
|
|||
|
/** @test */
|
|||
|
public function the_front_page_loads_for_anonymous_users() {
|
|||
|
$this->drupalGet('<front>');
|
|||
|
|
|||
|
$this->assertResponse(Response::HTTP_OK);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
This is a test someone can write, run and see the test pass.
|
|||
|
|
|||
|
They can then experiment by changing the values to make the test fail in different ways.
|
|||
|
|
|||
|
## What next?
|
|||
|
|
|||
|
Then, we tested anonymous users cannot access the administration pages, which is also already the case in Drupal core, and then authenticated users with the correct permissions could access them.
|
|||
|
|
|||
|
People were getting the idea by now, and we moved on to writing and testing some of our own code.
|