<p>As well as <a href="/daily/2024/06/03/writing-comments-first">writing comments first</a>, when writing tests, I sometimes like to write my tests backwards and start by writing the assertions first.</p>
<p>I know what I want to assert in the test, so it's an easy place to start.</p>
<p>I'll run it, see the error, fix it and continue working backwards.</p>
<p>For example, I could start with this:</p>
<pre><code class="php">public function testOnlyPostNodesAreShown(): void {
$assert = $this->assertSession();
$assert->pageTextContains('Post one');
$assert->pageTextContains('Post two');
$assert->pageTextNotContains('This is not a post');
}
</code></pre>
<p>This test will fail when I run it, but it makes me think about what I need to do to fix the error and how to do so in the best way.</p>
<p>In this case, I need to make a request to the page that should render the text:</p>
<pre><code class="php">public function testOnlyPostNodesAreShown(): void {
$this->drupalGet('/blog');
$assert = $this->assertSession();
$assert->pageTextContains('Post one');
$assert->pageTextContains('Post two');
$assert->pageTextNotContains('This is not a post');
}
</code></pre>
<p>This will still fail, as I also need to create the required posts:</p>
<pre><code class="php">public function testOnlyPostNodesAreShown(): void {
<p>As well as <a href="/daily/2024/06/03/writing-comments-first">writing comments first</a>, when writing tests, I sometimes like to write my tests backwards and start by writing the assertions first.</p>