r/PHPhelp • u/Chemicalclash • Jan 16 '22
Need help with basic php unit testing
Hi all,
Let's start of with the fact that I have very minimal experience in backend (PHP) development but I do enjoy learing about back-end as a front-end developer :). So I am currently at the stage where I want to learn some testing with php unit tests.
The problem Im having with this is that I do not know what exactly I should test inside my project.
I currently have a login, which includes the register part of the user. inside my class User, I created my public function as such:
<?php
public function register($data) {
$this->db->query('INSERT INTO users (username, email, account, password) VALUES(:username, :email, :account, :password)');
//Bind values
$this->db->bind(':username', $data['username']);
$this->db->bind(':email', $data['email']);
$this->db->bind(':account', $data['account']);
$this->db->bind(':password', $data['password']);
//Execute function
if ($this->db->execute()) {
return true;
} else {
return false;
}
}
?>
What should I test with php unit test and how should I go about this? Like does someone have an example of how to best test the functionality? I just want to do basic testing but id like to do it the right way.
Hope I explained it well.
Thanks for reading all :)
1
4
u/richardathome Jan 16 '22
public function register($data)
Test 1: Does it do what's expected of when given valid $data?
Test 2: Does it fail expectedly when $data isn't an array? (what happens when you pass it the number 2 for example)
Test 3: Does it fail expectedly if $data is empty? (Is it meant to fail or silently do nothing? - Test for that!)
Test 4: Does it fail expectedly if the email is blank?
Test 5: Does it fail expectedly if the email is too long to fit into the field your inserting it into?
Test 6: Is there any way for it to return something other than true or false? A test coverage report will highlight this)
You can code away some of those problems by changing your function to:
public function register(string $username, string $email, string $account, string $password):bool {}and using the named parameters instead of an array.
There's no way to call this WITHOUT specifying everything it needs. No need to test for when it doesn't get what it needs ;-)
Returning false from your function if it fails doesn't inform the called WHY it failed either. Did the DB go away? I raise custom exceptions like this:
public function register(string $username, string $email, string $account, string $password):void {
if (!$empty($username)) {throw new Exception('username cannot be empty'); }
// more validation here until I'm sure the values I'm about to process are valid
// Do the thing now I'm confident the data is ok. Any errors raised from now are unplanned/unexpected i.e. a coding bug (make a test to recreate the bug, then fix it so the test passes)
// no need to return anything - if it failed you'll get an descriptive exception message, if it worked it worked and no exception is raised! (you might want to return the User ID though)Your calling code would need to look like this:
try {$User->register('foo', '[email protected]', 'foobar', 'supersecret'); } catch (\Exception ($e) { // register failed! // handle the failure here (eg. redirect back to the registration page with the error message) } // register was successful
2
u/equilni Jan 17 '22
I would like to add to everyone's comments here.
I would drop the $data array and the expanding out the parameters like others have suggested and just use a class to pass the data:
class UserEntity {
public function __construct(
private string $username,
private string $email,
private string $account,
private string $password
) {}
public function getUsername(): string {
return $this->username;
}
public function getEmail(): string {
return $this->email;
}
public function getAccount(): string {
return $this->account;
}
public function getPassword(): string {
return $this->password;
}
}
class UserMapper{
public function __construct(
private PDO $db
) {}
public function register(UserEntity $user): bool {
$sth = $this->db->prepare('
INSERT INTO users (username, email, account, password)
VALUES (:username, :email, :account, :password)
');
return $sth->execute([
'username', $user->getUsername(),
'email', $user->getEmail(),
'account', $user->getAccount(),
'password', $user->getPassword()
]);
}
}2
u/dabenu Jan 17 '22
There's some decent tips in here, but I think the most important thing to note is that unit tests usually only test pure functions. There's nothing pure about this function though. It's literally just a db query. You could mock the db class, sure, but what are you testing then? Only your mock class...
So basically what I'm saying is, it doesn't make sense to test this method with a unit test in the first place.
1
u/itemluminouswadison Jan 16 '22
you give this class a mockobject version of the db object.
you run the method, then later assert that the mockobject received those method calls with those params.
i'd instead write a class that ONLY deals with "User" data persistence. Let's say, a "UserRepo"
class UserRepo {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function insert($data) {
...insert your code here
}
}then you inject an instance of UserRepo into your class that has the register method
public function register($data) {
$this->userRepo->insert($user);
}then your unit test simply tests that the UserRepo mock object had its insert method called with the user object
to take this further, you should create a User object that all the classes pass around.
you can also unit test your new UserRepo class and pass it a mock db object.
0
Jan 16 '22
[deleted]
3
u/Chemicalclash Jan 16 '22
Thank you, will do! Leuke naam btw 😆.
0
Jan 16 '22
[deleted]
3
u/HolyGonzo Jan 16 '22
I lived in the Netherlands for a few months. They don't have frikandel nor stamppot in the US :(
Although stamppot is not too hard to make, I have no idea how I would make frikandel.
3
u/richardathome Jan 16 '22
Didn't see your comment till I commented, but I pretty much paraphrased you with examples :)
3
u/[deleted] Jan 16 '22 edited Jan 16 '22