In this lesson, we will not write code but see a theory behind Unit or automated testing. One of the most common ways to write tests is to divide any function into three fazes, and they all start with an "A" letter. It's a "AAA". You can call it a framework: Arrange, Act, Assert. In most cases, you should stick to this plan for every function in your test.
Arrange
Add any data you need, any configuration. Build the scenario.
public function test_homepage_contains_non_empty_table(): void{ Product::create([ 'name' => 'Product 1', 'price' => 123, ]); $response = $this->get('/products'); $response->assertStatus(200); $response->assertDontSee(__('No products found'));}
Act
This is usually calling some API, calling some function, calling some URL. So, simulate the actual action of the user like you would be behind the browser doing the same thing.
public function test_homepage_contains_non_empty_table(): void{ Product::create([ 'name' => 'Product 1', 'price' => 123, ]); $response = $this->get('/products'); $response->assertStatus(200); $response->assertDontSee(__('No products found'));}
Assert
There can be multiple assertions. For example, we can assert the status, assert don't see some text, and also assert see the name of the product.
public function test_homepage_contains_non_empty_table(): void{ Product::create([ 'name' => 'Product 1', 'price' => 123, ]); $response = $this->get('/products'); $response->assertStatus(200); $response->assertDontSee(__('No products found')); $response->assertSee('Product 1'); }
Typically, there are multiple things for an arranged scenario, or it could be none. Then, there is usually one call for the action. And then there are multiple assertions. With multiple assertions, you shouldn't over-push on the assertions because you may bump into testing different scenarios. So it should be sometimes a different test.
Homepage of my site has many things: newest products, latest blog articles, teams, and few other things. Would it be right to have homepageTest.php file with one test method test_homepage_contains_all_content(), that includes:
or it better to have separate test methods for each section of the page?
As in many situations you asked for earlier, it's your personal preference :)
Copy that: AAA stands for Arrange, Act, and Assert.