First, I would like to rewrite the method as a small bit, if possible.
public function addUser(User $user) { if ($this->doesUserExist($user)) { throw new UserAlreadyExistException("The user ".$user->getUid()." already exists."); }
Another relevant method:
private function doesUserExist(User $user) { $users = $this->ldapRepository->findByUid($user->getUid()); return count($users) === 1; }
It’s immediately obvious that we basically have two tests:
- We verify that the method generates when the user exists.
- We verify that the method saves PbnlAccount if the user does not exist.
If you don’t see why we have these two tests, note that in this method there are two possible “threads”: one where the block is executed inside the if statement, and one where it is not executed.
Let's look at the first option:
public function testAddUserThrowsWhenUserExistsAlready() { $user = new User(); $user->setUid('123'); $ldapRepositoryMock = $this->createMock(LdapRepository::class); $ldapRepositoryMock ->method('findByUid') ->expects($this->once()) ->with('123') ->willReturn(new PbnlAccount()); $userRepository = new UserRepository($ldapRepositoryMock); $this->expectException(UserAlreadyExistException::class); $userRepository->addUser($user); }
The second test is left as an exercise for the reader :)
Yes, you will have to do some mockery of your case. You need to make fun of LdapRepository and LdapEntityManager as in this case.
Note 1: this code probably does not work, since I do not know the exact data about your code base (and I wrote it from my head), but this is not relevant. The point is you want to test the exception.
Note 2: I would rename your function to createNewPbnlAccountForUser(User $user) , which is longer but more descriptive of what it actually does.
Note 3: I'm not sure why you are returning $this->getUserByUid() , as this seems redundant (you already have a User), so I am sealing this case.