0

I have a my controller class like below

Class UserController {
  public function getName(){
    return "test_name"
  }

  public function hello(){
    return getName()."!"
  }
}

An accompanying unit test as seen below

use PHPUnit\Framework\TestCase;
use App\Http\Controllers\API\User\UserController;

class UserTest extends TestCase{
  public function testExample(){
   $mockGetName = $this->getMockBuilder(UserController::class)->onlyMethods(['getName'])->getMock();
   $mockGetName->method('getName')->willReturn("dummy");

   $userController = new $mockGetName();
   dump($userController->getName("test name"));
   }
}

When mocked getName() returns null instead of "dummy". Anyone have any idea why the specified return value is not being returned?

  • Do not do a `unit test` on a controller, that is a `feature test`. Also, you should use `Mockery` instead of `$this->getMockBuilder()`. I have no idea what that will return but `Mockery` is widely used, so everyone will know it more. – matiaslauriti Apr 11 '21 at 00:37
  • Thanks a lot for the Mockery shout. With regards to the former, I'm mocking out a simple helper function in a controller – Yoofi Brown-Pobee Apr 11 '21 at 21:41
  • Still, you do not test controllers as unit tests ! If you need a helper function and it is in a controller, that is a "mini" alarm that something is not designed correctly, as the controller should do whatever it needs in a run (few lines of code) or use a service/helper (a file/class in other places, but not the controller). – matiaslauriti Apr 11 '21 at 23:23

1 Answers1

1

Figured it out. I used createPartialMock instead of the mockBuilder and it returns what is needed.

$mockGetName = $this->createPartialMock(UserController::class, ['getName']);
$mockGetName->method('getName')->willReturn("test name");