oliverdavies.uk/source/_daily_emails/2022-11-14.md

44 lines
1.8 KiB
Markdown
Raw Normal View History

2024-01-03 20:00:00 +00:00
---
title: >
2024-02-07 20:01:19 +00:00
Camel-case or snake-case for test methods?
2024-01-03 20:00:00 +00:00
pubDate: 2022-11-14
permalink: >-
2024-02-07 20:01:19 +00:00
archive/2022/11/14/camel-case-or-snake-case-for-test-methods
2024-01-03 20:00:00 +00:00
tags:
2024-02-07 20:01:19 +00:00
- testing
2024-01-03 20:00:00 +00:00
---
When writing object-orientated code, particularly in PHP, you usually write method names using camel-case letters - such as:
```language-php
2024-01-03 20:00:00 +00:00
public function doSomething(): void {
// ...
}
```
This is also true when writing methods within a test class - only that the method name is prefixed with the word `test`:
```language-php
2024-01-03 20:00:00 +00:00
public function testSomething(): void {
}
```
This is probably expected and complies with the PSR code style standards like PSR-12.
Something that I've seen some PHP developers and some frameworks prefer is to write their test methods using snake-case letters and commonly removing the `test` prefix in favour of using an annotation:
```language-php
2024-01-03 20:00:00 +00:00
/** @test */
public function the_api_should_return_a_200_response_code_if_everything_is_ok(): void {
// ...
}
```
This is something that I've done myself for a while, but now I'm starting to reconsider both options.
Whilst it's more readable, especially for longer test names (which I like to write), it's not consistent with method names in non-test files or non-test methods in test files; it looks odd if I need to add another annotation (do I keep a single annotation on one line, or just those with multiple annotations on the separate lines), and to do this, I need to disable some code sniffer rules for code to pass the PHPCS checks.
If I used camel-cased names, I wouldn't need the PHPCS overrides, the annotations would be simpler, and the code would be more consistent - so I think I'll try that way again in the next tests that I write and see how it feels.
Which do you prefer, and which would you expect to see in your project?