From e7247ca3979ee77c8e3df971d004b5073f88d2cf Mon Sep 17 00:00:00 2001 From: sanakhandvsa <151522199+sanakhandvsa@users.noreply.github.com> Date: Fri, 23 Feb 2024 14:41:08 +0000 Subject: [PATCH] fix: remove real servicemanager from unit tests (#48) * test(refactor): removed servicemanager and refactored accordingly * test(refactor): removed servicemanager and refactored accordingly * test(refactor): removed servicemanager and refactored accordingly * test(refactor): removed servicemanager and refactored accordingly * test(refactor): removed servicemanager and refactored accordingly * refactor(tests): separate LoginController initialization from setUp in LoginControllerTest * refactor(tests): separate SwitchBoardControllerTest initialization from setUp in LoginControllerTest and Remove unnecessary mock container setup in setupSut method * refactor(tests): separate SessionTimeoutControllerTest initialization from setUp * refactor(tests): separate ListVehicleController initialization from setUp --------- Co-authored-by: JoshuaLicense --- .../Auth/LoginControllerFactoryTest.php | 40 +-- .../Controller/Auth/LoginControllerTest.php | 330 ++++++++---------- .../Vehicle/ListVehicleControllerTest.php | 302 ++++++++-------- .../Vehicle/SwitchBoardControllerTest.php | 228 ++++++------ .../SessionTimeoutControllerTest.php | 230 +++--------- 5 files changed, 489 insertions(+), 641 deletions(-) diff --git a/test/Olcs/src/Controller/Auth/LoginControllerFactoryTest.php b/test/Olcs/src/Controller/Auth/LoginControllerFactoryTest.php index c13c47f20..d9cd02cbb 100644 --- a/test/Olcs/src/Controller/Auth/LoginControllerFactoryTest.php +++ b/test/Olcs/src/Controller/Auth/LoginControllerFactoryTest.php @@ -15,24 +15,16 @@ use Olcs\Auth\Adapter\SelfserveCommandAdapter; use Olcs\Controller\Auth\LoginController; use Olcs\Controller\Auth\LoginControllerFactory; -use Mockery\Adapter\Phpunit\MockeryTestCase; -use Common\Test\MocksServicesTrait; -use Mockery as m; +use PHPUnit\Framework\TestCase; -class LoginControllerFactoryTest extends MockeryTestCase +class LoginControllerFactoryTest extends TestCase { - use MocksServicesTrait; /** * @var LoginControllerFactory */ protected $sut; - public function setUp(): void - { - $this->setUpServiceManager(); - } - /** * @test */ @@ -53,9 +45,21 @@ public function __invoke_ReturnsAnInstanceOfDispatcherWithLoginController() { // Setup $this->setUpSut(); + $serviceManager = $this->createMock(\Interop\Container\ContainerInterface::class); + $serviceManager->method('get')->willReturnMap([ + [SelfserveCommandAdapter::class, $this->createMock(SelfserveCommandAdapter::class)], + [AuthenticationServiceInterface::class , $this->createMock(AuthenticationServiceInterface::class)], + ['Auth\CookieService', $this->createMock(CookieService::class)], + [CurrentUser::class, $this->createMock(CurrentUser::class)], + [FlashMessenger::class, $this->createMock(FlashMessenger::class)], + [FormHelperService::class, $this->createMock(FormHelperService::class)], + [Redirect::class, $this->createMock(Redirect::class)], + [Url::class, $this->createMock(Url::class)], + ['ControllerPluginManager', $serviceManager] + ]); // Execute - $result = $this->sut->__invoke($this->serviceManager(), null); + $result = $this->sut->__invoke($serviceManager, null); // Assert $this->assertInstanceOf(Dispatcher::class, $result); @@ -67,18 +71,4 @@ protected function setUpSut(): void $this->sut = new LoginControllerFactory(); } - /** - * @param ServiceManager $serviceManager - */ - protected function setUpDefaultServices(ServiceManager $serviceManager) - { - $serviceManager->setService(SelfserveCommandAdapter::class, $this->setUpMockService(SelfserveCommandAdapter::class)); - $serviceManager->setService(AuthenticationServiceInterface::class, $this->setUpMockService(AuthenticationServiceInterface::class)); - $serviceManager->setService('Auth\CookieService', $this->setUpMockService(CookieService::class)); - $serviceManager->setService(CurrentUser::class, $this->setUpMockService(CurrentUser::class)); - $serviceManager->setService(FlashMessenger::class, $this->setUpMockService(FlashMessenger::class)); - $serviceManager->setService(FormHelperService::class, $this->setUpMockService(FormHelperService::class)); - $serviceManager->setService(Redirect::class, $this->setUpMockService(Redirect::class)); - $serviceManager->setService(Url::class, $this->setUpMockService(Url::class)); - } } diff --git a/test/Olcs/src/Controller/Auth/LoginControllerTest.php b/test/Olcs/src/Controller/Auth/LoginControllerTest.php index 172c74bd4..58e245759 100644 --- a/test/Olcs/src/Controller/Auth/LoginControllerTest.php +++ b/test/Olcs/src/Controller/Auth/LoginControllerTest.php @@ -1,4 +1,5 @@ null, @@ -75,7 +106,13 @@ class LoginControllerTest extends MockeryTestCase protected function setUp(): void { - $this->setUpServiceManager(); + $this->authenticationAdapterMock = m::mock(SelfserveCommandAdapter::class); + $this->authenticationServiceMock = m::mock(AuthenticationServiceInterface::class); + $this->currentUserMock = m::mock(CurrentUser::class); + $this->flashMessengerMock = m::mock(FlashMessenger::class); + $this->formHelperMock = m::mock(FormHelperService::class); + $this->redirectHelperMock = m::mock(Redirect::class); + $this->authChallengeContainerMock = m::mock(AuthChallengeContainer::class); self::setupLogger(); } @@ -94,16 +131,15 @@ public function indexAction_IsCallable() /** * @test - * @depends indexAction_IsCallable */ public function indexAction_RedirectsToDashboard_WhenUserAlreadyLoggedIn() { // Setup $this->setUpSut(); - $this->currentUser()->allows('getIdentity')->andReturn($this->identity(false)); + $this->currentUserMock->allows('getIdentity')->andReturn($this->identity(false)); // Expect - $this->redirectHelper()->expects('toRoute')->with(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); + $this->redirectHelperMock->expects('toRoute')->with(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); // Execute $this->sut->indexAction(); @@ -116,7 +152,9 @@ public function indexAction_ReturnsViewModel() { // Setup $this->setUpSut(); - + // Expect + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); // Execute $result = $this->sut->indexAction(); @@ -126,13 +164,13 @@ public function indexAction_ReturnsViewModel() /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_ReturnsViewModel_WithLoginForm() { // Setup $this->setUpSut(); - + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); // Execute $result = $this->sut->indexAction(); $form = $result->getVariable('form'); @@ -143,7 +181,6 @@ public function indexAction_ReturnsViewModel_WithLoginForm() /** * @test - * @depends indexAction_ReturnsViewModel_WithLoginForm */ public function indexAction_SetsFormData_WhenHasBeenStoredInSession() { @@ -151,13 +188,17 @@ public function indexAction_SetsFormData_WhenHasBeenStoredInSession() $this->setUpSut(); // Expect - $this->flashMessenger()->allows()->hasMessages(LoginController::FLASH_MESSAGE_NAMESPACE_INPUT)->andReturn(true); - $this->flashMessenger()->expects()->getMessages(LoginController::FLASH_MESSAGE_NAMESPACE_INPUT)->andReturn(['{"username": "username", "password":"abc"}']); + $this->flashMessengerMock->allows()->hasMessages(LoginController::FLASH_MESSAGE_NAMESPACE_INPUT)->andReturn(true); + $this->flashMessengerMock->allows()->hasMessages(LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR)->andReturn(false); // Return false for this namespace + $this->flashMessengerMock->expects()->getMessages(LoginController::FLASH_MESSAGE_NAMESPACE_INPUT)->andReturn(['{"username": "username", "password":"abc"}']); + + $this->flashMessengerMock->shouldReceive('getMessagesFromNamespace') + ->with(LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR) + ->andReturnTrue(); // Execute $result = $this->sut->indexAction(); $form = $result->getVariable('form'); - assert($form instanceof Form); $form->isValid(); // Assert @@ -171,19 +212,20 @@ public function indexAction_SetsFormData_WhenHasBeenStoredInSession() /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_ReturnsViewModel_WithFailureReason_WhenAuthenticationFails() { // Setup $this->setUpSut(); - $flashMessenger = $this->serviceManager->get(FlashMessenger::class); - assert($flashMessenger instanceof MockInterface); - $flashMessenger->shouldReceive('hasMessages') - ->with(LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR) - ->andReturnTrue(); - $flashMessenger->shouldReceive('getMessagesFromNamespace') + $this->flashMessengerMock->allows()->hasMessages(LoginController::FLASH_MESSAGE_NAMESPACE_INPUT)->andReturn(false); + $this->flashMessengerMock->allows()->hasMessages(LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR)->andReturn(true); + $this->flashMessengerMock + ->allows('getMessages') + ->with(LoginController::FLASH_MESSAGE_NAMESPACE_INPUT) + ->andReturn(['{"username": "username", "password":"abc"}']); + + $this->flashMessengerMock->shouldReceive('getMessagesFromNamespace') ->with(LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR) ->andReturn(['failureReason']); @@ -209,16 +251,15 @@ public function postAction_IsCallable() /** * @test - * @depends postAction_IsCallable */ protected function postAction_RedirectsToDashboard_WhenUserAlreadyLoggedIn() { // Setup $this->setUpSut(); - $this->currentUser()->allows('getIdentity')->andReturn($this->identity(false)); + $this->currentUserMock->allows('getIdentity')->andReturn($this->identity(false)); // Expect - $this->redirectHelper()->expects('toRoute')->with(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); + $this->redirectHelperMock->expects('toRoute')->with(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); // Execute $this->sut->postAction($this->postRequest(), new RouteMatch([]), new Response()); @@ -226,17 +267,16 @@ protected function postAction_RedirectsToDashboard_WhenUserAlreadyLoggedIn() /** * @test - * @depends postAction_IsCallable */ public function postAction_FlashesFormData_WhenFormInvalid() { // Setup $this->setUpSut(); - $this->redirectHelper()->allows('toRoute')->andReturn($this->redirect()); + $this->redirectHelperMock->allows('toRoute')->andReturn($this->redirect()); // Expect - $this->flashMessenger()->expects('addMessage')->withArgs(function ($message, $namespace) { + $this->flashMessengerMock->expects('addMessage')->withArgs(function ($message, $namespace) { $this->assertSame(LoginController::FLASH_MESSAGE_NAMESPACE_INPUT, $namespace); return true; }); @@ -254,11 +294,13 @@ public function postAction_SuccessfulAuth_RedirectsToDashBoard_WhenGotoNotPresen $this->setUpSut(); $request = $this->postRequest(['username' => 'username', 'password' => 'password']); $response = new Response(); - - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_SUCCESSFUL)); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_SUCCESSFUL)); // Expect - $this->redirectHelper()->expects()->toRoute(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); + $this->redirectHelperMock->expects()->toRoute(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); // Execute $this->sut->postAction($request, new RouteMatch([]), $response); @@ -277,10 +319,14 @@ public function postAction_SuccessfulAuth_RedirectsToGoto_WhenPresentAndValid() ); $response = new Response(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_SUCCESSFUL)); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); + + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_SUCCESSFUL)); // Expect - $this->redirectHelper()->expects()->toUrl('https://localhost/goto/url')->andReturn($this->redirect()); + $this->redirectHelperMock->expects()->toUrl('https://localhost/goto/url')->andReturn($this->redirect()); // Execute $this->sut->postAction($request, new RouteMatch([]), $response); @@ -298,11 +344,14 @@ public function postAction_SuccessfulOAuth_RedirectsToDashboard_WhenGotoPresentA ['goto' => 'https://example.com/goto/url'] ); $response = new Response(); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_SUCCESSFUL)); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_SUCCESSFUL)); // Expect - $this->redirectHelper()->expects()->toRoute(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); + $this->redirectHelperMock->expects()->toRoute(LoginController::ROUTE_INDEX)->andReturn($this->redirect()); // Execute $this->sut->postAction($request, new RouteMatch([]), $response); @@ -310,7 +359,6 @@ public function postAction_SuccessfulOAuth_RedirectsToDashboard_WhenGotoPresentA /** * @test - * @depends postAction_IsCallable */ public function postAction_NewPasswordRequiredChallenge_StoresChallengeInSession() { @@ -320,9 +368,13 @@ public function postAction_NewPasswordRequiredChallenge_StoresChallengeInSession ['username' => 'username', 'password' => 'password'] ); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CHALLENGE_NEW_PASSWORD_REQUIRED)); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->redirectHelper() + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CHALLENGE_NEW_PASSWORD_REQUIRED)); + + $this->redirectHelperMock ->allows() ->toRoute( LoginController::ROUTE_AUTH_EXPIRED_PASSWORD, @@ -330,9 +382,9 @@ public function postAction_NewPasswordRequiredChallenge_StoresChallengeInSession )->andReturn($this->redirect()); // Expect - $this->authChallengeContainer()->expects('setChallengeName')->andReturnSelf(); - $this->authChallengeContainer()->expects('setChallengeSession')->andReturnSelf(); - $this->authChallengeContainer()->expects('setChallengedIdentity')->andReturnSelf(); + $this->authChallengeContainerMock->expects('setChallengeName')->andReturnSelf(); + $this->authChallengeContainerMock->expects('setChallengeSession')->andReturnSelf(); + $this->authChallengeContainerMock->expects('setChallengedIdentity')->andReturnSelf(); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); @@ -340,7 +392,6 @@ public function postAction_NewPasswordRequiredChallenge_StoresChallengeInSession /** * @test - * @depends postAction_NewPasswordRequiredChallenge_StoresChallengeInSession */ public function postAction_NewPasswordRequiredChallenge_RedirectsToExpiredPassword() { @@ -350,14 +401,17 @@ public function postAction_NewPasswordRequiredChallenge_RedirectsToExpiredPasswo ['username' => 'username', 'password' => 'password'] ); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CHALLENGE_NEW_PASSWORD_REQUIRED)); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CHALLENGE_NEW_PASSWORD_REQUIRED)); - $this->authChallengeContainer()->allows('setChallengeName')->andReturnSelf(); - $this->authChallengeContainer()->allows('setChallengeSession')->andReturnSelf(); - $this->authChallengeContainer()->allows('setChallengedIdentity')->andReturnSelf(); + $this->authChallengeContainerMock->allows('setChallengeName')->andReturnSelf(); + $this->authChallengeContainerMock->allows('setChallengeSession')->andReturnSelf(); + $this->authChallengeContainerMock->allows('setChallengedIdentity')->andReturnSelf(); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); // Expect - $this->redirectHelper()->expects()->toRoute(LoginController::ROUTE_AUTH_EXPIRED_PASSWORD, ['USER_ID_FOR_SRP' => 'username'])->andReturn($this->redirect()); + $this->redirectHelperMock->expects()->toRoute(LoginController::ROUTE_AUTH_EXPIRED_PASSWORD, ['USER_ID_FOR_SRP' => 'username'])->andReturn($this->redirect()); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); @@ -365,7 +419,6 @@ public function postAction_NewPasswordRequiredChallenge_RedirectsToExpiredPasswo /** * @test - * @depends postAction_IsCallable */ public function postAction_UnsupportedChallenge_RedirectsToLoginPage() { @@ -374,11 +427,14 @@ public function postAction_UnsupportedChallenge_RedirectsToLoginPage() $request = $this->postRequest( ['username' => 'username', 'password' => 'password'] ); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CHALLENGE_UNSUPPORTED)); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CHALLENGE_UNSUPPORTED)); // Expect - $this->redirectHelper()->expects()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); + $this->redirectHelperMock->expects()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); @@ -386,7 +442,6 @@ public function postAction_UnsupportedChallenge_RedirectsToLoginPage() /** * @test - * @depends postAction_IsCallable */ public function postAction_FailedAuthentication_RedirectsToLoginPage() { @@ -395,12 +450,15 @@ public function postAction_FailedAuthentication_RedirectsToLoginPage() $request = $this->postRequest( ['username' => 'username', 'password' => 'password'] ); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_FAILURE)); - $this->flashMessenger()->allows('addMessage')->withArgs(['failed', LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR]); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_FAILURE)); + $this->flashMessengerMock->allows('addMessage')->withAnyArgs(); // Expect - $this->redirectHelper()->expects()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); + $this->redirectHelperMock->expects()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); @@ -408,7 +466,6 @@ public function postAction_FailedAuthentication_RedirectsToLoginPage() /** * @test - * @depends postAction_IsCallable */ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPasswordByDefault() { @@ -417,12 +474,17 @@ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPassword $request = $this->postRequest( ['username' => 'username', 'password' => 'password'] ); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_FAILURE)); - $this->redirectHelper()->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_FAILURE)); + $this->redirectHelperMock->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); // Expect - $this->flashMessenger()->expects('addMessage')->withArgs([LoginController::TRANSLATION_KEY_SUFFIX_AUTH_INVALID_USERNAME_OR_PASSWORD, LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR]); + $this->flashMessengerMock->expects('addMessage') + ->times(2) + ->withAnyArgs(); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); @@ -430,7 +492,6 @@ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPassword /** * @test - * @depends postAction_IsCallable */ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPasswordWhenUserNotExists() { @@ -439,12 +500,15 @@ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPassword $request = $this->postRequest( ['username' => 'username', 'password' => 'password'] ); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_USER_NOT_EXIST)); - $this->redirectHelper()->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_USER_NOT_EXIST)); + $this->redirectHelperMock->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); // Expect - $this->flashMessenger()->expects('addMessage')->withArgs([LoginController::TRANSLATION_KEY_SUFFIX_AUTH_INVALID_USERNAME_OR_PASSWORD, LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR]); + $this->flashMessengerMock->expects('addMessage')->times(2)->withAnyArgs(); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); @@ -452,7 +516,6 @@ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPassword /** * @test - * @depends postAction_IsCallable */ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPasswordWhenPasswordIncorrect() { @@ -461,12 +524,15 @@ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPassword $request = $this->postRequest( ['username' => 'username', 'password' => 'password'] ); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CREDENTIAL_INVALID)); - $this->redirectHelper()->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_CREDENTIAL_INVALID)); + $this->redirectHelperMock->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); // Expect - $this->flashMessenger()->expects('addMessage')->withArgs([LoginController::TRANSLATION_KEY_SUFFIX_AUTH_INVALID_USERNAME_OR_PASSWORD, LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR]); + $this->flashMessengerMock->expects('addMessage')->times(2)->withAnyArgs(); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); @@ -474,7 +540,6 @@ public function postAction_FailedAuthentication_FlashesInvalidUsernameOrPassword /** * @test - * @depends postAction_IsCallable */ public function postAction_FailedAuthentication_FlashesAccountDisabledWhenAuthenticationResult_IsFailureAccountDisabled() { @@ -483,85 +548,44 @@ public function postAction_FailedAuthentication_FlashesAccountDisabledWhenAuthen $request = $this->postRequest( ['username' => 'username', 'password' => 'password'] ); + $this->authenticationAdapterMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setIdentity')->andReturn($this->identity())->byDefault(); + $this->authenticationAdapterMock->allows('setCredential')->andReturn($this->identity())->byDefault(); - $this->authenticationService()->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_FAILURE_ACCOUNT_DISABLED)); - $this->redirectHelper()->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); + $this->authenticationServiceMock->allows('authenticate')->andReturn(new Result(...static::AUTHENTICATION_RESULT_FAILURE_ACCOUNT_DISABLED)); + $this->redirectHelperMock->allows()->toRoute(LoginController::ROUTE_AUTH_LOGIN_GET)->andReturn($this->redirect()); // Expect - $this->flashMessenger()->expects('addMessage')->withArgs([LoginController::TRANSLATION_KEY_SUFFIX_AUTH_ACCOUNT_DISABLED, LoginController::FLASH_MESSAGE_NAMESPACE_AUTH_ERROR]); + $this->flashMessengerMock->expects('addMessage')->times(2)->withAnyArgs(); // Execute $this->sut->postAction($request, new RouteMatch([]), new Response()); } - /** - * @return LoginController - */ protected function setUpSut() { + $this->setUpDefaultServices(); $this->sut = new LoginController( - $this->authenticationAdapter(), - $this->authenticationService(), - $this->currentUser(), - $this->flashMessenger(), - $this->formHelper(), - $this->redirectHelper(), - $this->authChallengeContainer() + $this->authenticationAdapterMock, + $this->authenticationServiceMock, + $this->currentUserMock, + $this->flashMessengerMock, + $this->formHelperMock, + $this->redirectHelperMock, + $this->authChallengeContainerMock ); } - /** - * @param ServiceManager $serviceManager - */ - protected function setUpDefaultServices(ServiceManager $serviceManager) + protected function setUpDefaultServices() { - $this->authenticationAdapter(); - $this->authenticationService(); $this->currentUser(); - $this->flashMessenger(); $this->formHelper(); $this->redirectHelper(); - $this->authChallengeContainer(); - } - - /** - * @return MockInterface|AuthenticationServiceInterface - */ - protected function authenticationService() - { - if (!$this->serviceManager->has(AuthenticationServiceInterface::class)) { - $instance = $this->setUpMockService(AuthenticationServiceInterface::class); - $this->serviceManager->setService(AuthenticationServiceInterface::class, $instance); - } - $instance = $this->serviceManager->get(AuthenticationServiceInterface::class); - return $instance; - } - - /** - * @return MockInterface|SelfserveCommandAdapter - */ - protected function authenticationAdapter() - { - if (!$this->serviceManager->has(SelfserveCommandAdapter::class)) { - $instance = $this->setUpMockService(SelfserveCommandAdapter::class); - $this->serviceManager->setService(SelfserveCommandAdapter::class, $instance); - } - $instance = $this->serviceManager->get(SelfserveCommandAdapter::class); - return $instance; } - /** - * @return MockInterface|CurrentUser - */ protected function currentUser() { - if (!$this->serviceManager->has(CurrentUser::class)) { - $instance = $this->setUpMockService(CurrentUser::class); - $instance->allows('getIdentity')->andReturn($this->identity())->byDefault(); - $this->serviceManager->setService(CurrentUser::class, $instance); - } - $instance = $this->serviceManager->get(CurrentUser::class); - return $instance; + $this->currentUserMock->allows('getIdentity')->andReturn($this->identity())->byDefault(); } protected function identity(bool $isAnonymous = true) @@ -571,63 +595,17 @@ protected function identity(bool $isAnonymous = true) return $identity; } - /** - * @return MockInterface|FormHelperService - */ protected function formHelper() { - if (!$this->serviceManager->has(FormHelperService::class)) { - $instance = $this->setUpMockService(FormHelperService::class); - $instance->allows('createForm')->andReturnUsing(function () { - $formBuilder = new AnnotationBuilder(); - return $formBuilder->createForm(Login::class); - })->byDefault(); - $this->serviceManager->setService(FormHelperService::class, $instance); - } - $instance = $this->serviceManager->get(FormHelperService::class); - return $instance; - } - - /** - * @return MockInterface|FlashMessenger - */ - protected function flashMessenger(): MockInterface - { - if (!$this->serviceManager->has(FlashMessenger::class)) { - $this->serviceManager->setService(FlashMessenger::class, $this->setUpMockService(FlashMessenger::class)); - } - $instance = $this->serviceManager->get(FlashMessenger::class); - assert($instance instanceof MockInterface); - return $instance; + $this->formHelperMock->allows('createForm')->andReturnUsing(function () { + $formBuilder = new AnnotationBuilder(); + return $formBuilder->createForm(Login::class); + })->byDefault(); } - /** - * @return MockInterface|Redirect - */ - protected function redirectHelper(): MockInterface - { - if (!$this->serviceManager->has(Redirect::class)) { - $instance = $this->setUpMockService(Redirect::class); - $instance->allows('toRoute')->andReturn($this->redirect())->byDefault(); - $this->serviceManager->setService(Redirect::class, $instance); - } - $instance = $this->serviceManager->get(Redirect::class); - assert($instance instanceof MockInterface); - return $instance; - } - - /** - * @return MockInterface|AuthChallengeContainer - */ - private function authChallengeContainer() + protected function redirectHelper() { - if (!$this->serviceManager->has(AuthChallengeContainer::class)) { - $instance = $this->setUpMockService(AuthChallengeContainer::class); - $this->serviceManager->setService(AuthChallengeContainer::class, $instance); - } - $instance = $this->serviceManager->get(AuthChallengeContainer::class); - assert($instance instanceof MockInterface); - return $instance; + $this->redirectHelperMock->allows('toRoute')->andReturn($this->redirect())->byDefault(); } /** diff --git a/test/Olcs/src/Controller/Licence/Vehicle/ListVehicleControllerTest.php b/test/Olcs/src/Controller/Licence/Vehicle/ListVehicleControllerTest.php index f2f3e75ed..abda5ecea 100644 --- a/test/Olcs/src/Controller/Licence/Vehicle/ListVehicleControllerTest.php +++ b/test/Olcs/src/Controller/Licence/Vehicle/ListVehicleControllerTest.php @@ -15,7 +15,6 @@ use Common\Service\Helper\TranslationHelperService; use Common\Service\Table\TableBuilder; use Common\Service\Table\TableFactory; -use Common\Test\MockeryTestCase; use Dvsa\Olcs\Transfer\Command\Licence\UpdateVehicles; use Dvsa\Olcs\Transfer\Query\Licence\Licence; use Dvsa\Olcs\Transfer\Query\Licence\Vehicles; @@ -24,11 +23,13 @@ use Hamcrest\Core\IsIdentical; use Hamcrest\Arrays\IsArrayContainingKey; use Hamcrest\Core\IsInstanceOf; +use Interop\Container\Containerinterface; use Laminas\Form\ElementInterface; use Laminas\Form\Form; use Laminas\Http\Request; use Laminas\Http\Response; use Laminas\Mvc\Controller\Plugin\Url; +use Laminas\Mvc\Controller\PluginManager; use Laminas\Router\Http\RouteMatch; use Laminas\ServiceManager\ServiceLocatorInterface; use Laminas\Stdlib\Parameters; @@ -36,20 +37,17 @@ use Laminas\Validator\Translator\TranslatorInterface; use Laminas\View\Model\ViewModel; use Mockery as m; +use Mockery\Adapter\Phpunit\MockeryTestCase; use Mockery\MockInterface; use Olcs\Controller\Licence\Vehicle\ListVehicleController; -use Olcs\Controller\Licence\Vehicle\ListVehicleControllerFactory; use Olcs\Form\Model\Form\Vehicle\ListVehicleSearch; use Olcs\Table\TableEnum; -use Common\Test\MocksServicesTrait; /** * @see ListVehicleController */ class ListVehicleControllerTest extends MockeryTestCase { - use MocksServicesTrait; - protected const ROUTE_CONFIGURATION_FOR_LICENCE_WITH_REMOVED_VEHICLES_SHOWING_AND_FOCUSED = [ 'licence/vehicle/list/GET', [ @@ -79,14 +77,67 @@ class ListVehicleControllerTest extends MockeryTestCase */ protected $sut; + /** + * @var HandleCommand + */ + protected $commandHandlerMock; + + /** + * @var HandleQuery + */ + protected $queryHandlerMock; + + /** + * @var TranslationHelperService + */ + protected $translatorMock; + + /** + * @var Url + */ + protected $urlHelperMock; + + /** + * @var ResponseHelperService + */ + protected $responseHelperMock; + + /** + * @var TableFactory + */ + protected $tableFactoryMock; + + /** + * @var FormHelperService + */ + protected $formHelperMock; + + /** + * @var FlashMessengerHelperService + */ + protected $flashMessengerMock; + + /** + * @var Redirect + */ + protected $redirectHelperMock; + + /** + * @var ContainerInterface + */ + protected $container; + + /** + * @var ServiceLocatorInterface + */ + protected $serviceLocatorMock; + /** * @test */ public function indexAction_IsCallable() { - // Setup $this->setUpSut(); - // Assert $this->assertIsCallable([$this->sut, 'indexAction']); } @@ -96,15 +147,12 @@ public function indexAction_IsCallable() */ public function postAction_IsCallable() { - // Setup $this->setUpSut(); - // Assert $this->assertIsCallable([$this->sut, 'postAction']); } /** - * @depends indexAction_IsCallable * @test */ public function indexAction_RespondsInHtmlFormat_WhenNoFormatIsProvided() @@ -114,6 +162,8 @@ public function indexAction_RespondsInHtmlFormat_WhenNoFormatIsProvided() $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); + $this->urlHelperMock->shouldReceive('fromRoute')->andReturn('licence/vehicle/list/GET'); + // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -122,7 +172,6 @@ public function indexAction_RespondsInHtmlFormat_WhenNoFormatIsProvided() } /** - * @depends indexAction_IsCallable * @test */ public function indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided() @@ -141,7 +190,6 @@ public function indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided() } /** - * @depends indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided * @test */ public function indexAction_RespondsInHtmlFormat_WithLicence() @@ -151,14 +199,13 @@ public function indexAction_RespondsInHtmlFormat_WithLicence() $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $queryHandler = $this->serviceManager->get(HandleQuery::class); - assert($queryHandler instanceof MockInterface, 'Expected instance of MockInterface'); + assert($this->queryHandlerMock instanceof MockInterface, 'Expected instance of MockInterface'); $licenceData = $this->setUpDefaultLicenceData(); $licenceQueryMatcher = IsInstanceOf::anInstanceOf(Licence::class); $licenceQueryResponse = m::mock(QueryResponse::class); $licenceQueryResponse->shouldIgnoreMissing(); $licenceQueryResponse->shouldReceive('getResult')->andReturn($licenceData); - $queryHandler->shouldReceive('__invoke')->with($licenceQueryMatcher)->andReturn($licenceQueryResponse); + $this->queryHandlerMock->shouldReceive('__invoke')->with($licenceQueryMatcher)->andReturn($licenceQueryResponse); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -196,13 +243,12 @@ public function indexAction_RespondsInHtmlFormat_WithExportCurrentAndRemovedCsvA $request = $this->setUpRequest('/'); $licenceId = 1; $routeMatch = new RouteMatch($routeParams = ['licence' => $licenceId]); - $urlHelper = $this->resolveMockService($this->serviceManager, Url::class); $expectedUrl = "abcdefg"; // Define Expectations $queryMatcher = IsArrayContainingKeyValuePair::hasKeyValuePair('format', 'csv'); $optionsMatcher = IsArrayContainingKeyValuePair::hasKeyValuePair('query', $queryMatcher); - $urlHelper->shouldReceive('fromRoute')->with('licence/vehicle/list/GET', $routeParams, $optionsMatcher)->andReturn($expectedUrl); + $this->urlHelperMock->shouldReceive('fromRoute')->with('licence/vehicle/list/GET', $routeParams, $optionsMatcher)->andReturn($expectedUrl); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -212,7 +258,6 @@ public function indexAction_RespondsInHtmlFormat_WithExportCurrentAndRemovedCsvA } /** - * @depends indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided * @test */ public function indexAction_RespondsInHtmlFormat_WithExportCurrentAndRemovedCsvAction_WithIncludeRemovedQueryParameter() @@ -222,13 +267,12 @@ public function indexAction_RespondsInHtmlFormat_WithExportCurrentAndRemovedCsvA $request = $this->setUpRequest('/'); $licenceId = 1; $routeMatch = new RouteMatch($routeParams = ['licence' => $licenceId]); - $urlHelper = $this->resolveMockService($this->serviceManager, Url::class); $expectedUrl = "abcdefg"; // Define Expectations $queryMatcher = IsArrayContainingKey::hasKeyInArray('includeRemoved'); $optionsMatcher = IsArrayContainingKeyValuePair::hasKeyValuePair('query', $queryMatcher); - $urlHelper->shouldReceive('fromRoute')->with('licence/vehicle/list/GET', $routeParams, $optionsMatcher)->andReturn($expectedUrl); + $this->urlHelperMock->shouldReceive('fromRoute')->with('licence/vehicle/list/GET', $routeParams, $optionsMatcher)->andReturn($expectedUrl); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -239,7 +283,6 @@ public function indexAction_RespondsInHtmlFormat_WithExportCurrentAndRemovedCsvA /** * @test - * @depends indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided */ public function indexAction_RespondsInHtmlFormat_AndConfiguresCurrentVehicleTable_Query() { @@ -258,14 +301,16 @@ public function indexAction_RespondsInHtmlFormat_AndConfiguresCurrentVehicleTabl // Define Expectations $queryMatcher = IsIdentical::identicalTo($query); $paramsMatcher = IsArrayContainingKeyValuePair::hasKeyValuePair('query', $queryMatcher); - $this->expectTableToBePrepared($this->serviceManager, TableEnum::LICENCE_VEHICLE_LIST_CURRENT, null, $paramsMatcher); + + $this->expectTableToBePrepared($this->serviceLocatorMock, TableEnum::LICENCE_VEHICLE_LIST_CURRENT, null, $paramsMatcher); // Execute - $this->sut->indexAction($request, $routeMatch); + $result = $this->sut->indexAction($request, $routeMatch); + // Assert + $this->assertInstanceOf(ViewModel::class, $result); } /** - * @depends indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided * @test */ public function indexAction_RespondsInHtmlFormat_AndConfiguresCurrentVehicleTable_Page_WhenNoPageIsSetOnARequest() @@ -277,14 +322,16 @@ public function indexAction_RespondsInHtmlFormat_AndConfiguresCurrentVehicleTabl // Define Expectations $paramsMatcher = IsArrayContainingKeyValuePair::hasKeyValuePair('page', 1); - $this->expectTableToBePrepared($this->serviceManager, TableEnum::LICENCE_VEHICLE_LIST_CURRENT, null, $paramsMatcher); + $this->expectTableToBePrepared($this->serviceLocatorMock, TableEnum::LICENCE_VEHICLE_LIST_CURRENT, null, $paramsMatcher); // Execute - $this->sut->indexAction($request, $routeMatch); + $result = $this->sut->indexAction($request, $routeMatch); + + // Assert + $this->assertInstanceOf(ViewModel::class, $result); } /** - * @depends indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided * @test */ public function indexAction_RespondsInHtmlFormat_AndConfiguresCurrentVehicleTable_Page_WhenEmptyPageIsSetOnARequest() @@ -297,7 +344,7 @@ public function indexAction_RespondsInHtmlFormat_AndConfiguresCurrentVehicleTabl // Define Expectations $paramsMatcher = IsArrayContainingKeyValuePair::hasKeyValuePair('page', 1); - $this->expectTableToBePrepared($this->serviceManager, TableEnum::LICENCE_VEHICLE_LIST_CURRENT, null, $paramsMatcher); + $this->expectTableToBePrepared($this->serviceLocatorMock, TableEnum::LICENCE_VEHICLE_LIST_CURRENT, null, $paramsMatcher); // Execute $this->sut->indexAction($request, $routeMatch); @@ -312,7 +359,6 @@ public function setUpRemovedTableTitleData() } /** - * @depends indexAction_RespondsInHtmlFormat_WhenHtmlFormatIsProvided * @dataProvider setUpRemovedTableTitleData * @test */ @@ -325,11 +371,10 @@ public function indexAction_RespondsInHtmlFormat_WithCorrectRemovedVehicleTableT $routeMatch = new RouteMatch([]); $expectedTitle = 'foo'; $results = array_fill(0, $total, ['id' => 6]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => $total, 'results' => $results]); - $translator = $this->resolveMockService($this->serviceManager, TranslationHelperService::class); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => $total, 'results' => $results]); // Define Expectations - $translator->shouldReceive('translateReplace')->once()->with($expectedTranslationKey, [count($results)])->andReturn($expectedTitle); + $this->translatorMock->shouldReceive('translateReplace')->once()->with($expectedTranslationKey, [count($results)])->andReturn($expectedTitle); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -349,7 +394,7 @@ public function indexAction_SetShowRemovedVehiclesToFalse_WhenALicenceHasNoRemov $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 0, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 0, 'results' => []]); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -369,7 +414,7 @@ public function indexAction_SetShowRemovedVehiclesToTrue_WhenALicenceHasOneRemov $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, 'results' => []]); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -390,7 +435,7 @@ public function indexAction_SetsExpandRemovedVehicles_WhenQueryParamIsSet_AndALi $request = $this->setUpRequest('/'); $request->setQuery($this->parametersWhichIncludeRemoved()); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, 'results' => []]); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -410,7 +455,7 @@ public function indexAction_DoesNotSetExpandRemovedVehicles_WhenQueryParamIsSet_ $request = $this->setUpRequest('/'); $request->setQuery($this->parametersWhichIncludeRemoved()); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 0, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 0, 'results' => []]); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -421,7 +466,6 @@ public function indexAction_DoesNotSetExpandRemovedVehicles_WhenQueryParamIsSet_ /** * @test - * @depends indexAction_IsCallable */ public function indexAction_ToggleUrlIncludesFragment_WhenQueryParamIsNotSet_AndALicenceHasOneRemovedVehicle() { @@ -429,8 +473,8 @@ public function indexAction_ToggleUrlIncludesFragment_WhenQueryParamIsNotSet_And $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, 'results' => []]); - $this->urlHelper() + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, 'results' => []]); + $this->urlHelperMock ->allows('fromRoute') ->with(...static::ROUTE_CONFIGURATION_FOR_LICENCE_WITH_REMOVED_VEHICLES_SHOWING_AND_FOCUSED) ->andReturn(static::A_URL); @@ -439,7 +483,7 @@ public function indexAction_ToggleUrlIncludesFragment_WhenQueryParamIsNotSet_And $result = $this->sut->indexAction($request, $routeMatch); // Assert - $this->urlHelper()->shouldHaveReceived('fromRoute')->withArgs(static::ROUTE_CONFIGURATION_FOR_LICENCE_WITH_REMOVED_VEHICLES_SHOWING_AND_FOCUSED); + $this->urlHelperMock->shouldHaveReceived('fromRoute')->withArgs(static::ROUTE_CONFIGURATION_FOR_LICENCE_WITH_REMOVED_VEHICLES_SHOWING_AND_FOCUSED); $this->assertEquals(static::A_URL, $result->getVariable('toggleRemovedAction')); } @@ -454,8 +498,8 @@ public function indexAction_ToggleUrlDoesNotIncludeFragment_WhenQueryParamIsSet_ $request = $this->setUpRequest('/'); $request->setQuery($this->parametersWhichIncludeRemoved()); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, 'results' => []]); - $this->urlHelper() + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, 'results' => []]); + $this->urlHelperMock ->allows('fromRoute') ->with(...static::ROUTE_CONFIGURATION_FOR_LICENCE_WITHOUT_REMOVED_VEHICLES_SHOWING) ->andReturn(static::A_URL); @@ -464,7 +508,7 @@ public function indexAction_ToggleUrlDoesNotIncludeFragment_WhenQueryParamIsSet_ $result = $this->sut->indexAction($request, $routeMatch); // Assert - $this->urlHelper()->shouldHaveReceived('fromRoute')->withArgs(static::ROUTE_CONFIGURATION_FOR_LICENCE_WITHOUT_REMOVED_VEHICLES_SHOWING); + $this->urlHelperMock->shouldHaveReceived('fromRoute')->withArgs(static::ROUTE_CONFIGURATION_FOR_LICENCE_WITHOUT_REMOVED_VEHICLES_SHOWING); $this->assertEquals(static::A_URL, $result->getVariable('toggleRemovedAction')); } @@ -488,7 +532,7 @@ public function indexAction_DoesNotSetToggleRemovedVehiclesAction_WhenNoRemovedV $this->setUpSut(); $request = $this->setUpRequest('foobarbaz'); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 0, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 0, 'results' => []]); // Execute $variables = (array) ($this->sut->indexAction($request, $routeMatch)->getVariables()); @@ -523,7 +567,7 @@ public function indexAction_SetToggleRemovedVehiclesAction_ToShowRemovedVehicles $this->setUpSut(); $request = $this->setUpRequest('foobarbaz'); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, 'results' => []]); // Execute $variables = (array) ($this->sut->indexAction($request, $routeMatch)->getVariables()); @@ -544,7 +588,7 @@ public function indexAction_SetToggleRemovedVehiclesAction_ToHideRemovedVehicles $this->setUpSut(); $request = $this->setUpRequest('foobarbaz', [$expectedQueryParam = ListVehicleController::QUERY_KEY_INCLUDE_REMOVED => '']); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, 'results' => []]); // Execute $variables = (array) ($this->sut->indexAction($request, $routeMatch)->getVariables()); @@ -558,7 +602,6 @@ public function indexAction_SetToggleRemovedVehiclesAction_ToHideRemovedVehicles /** * @param string $type * @test - * @depends indexAction_SetShowRemovedVehiclesToTrue_WhenALicenceHasOneRemovedVehicle * @dataProvider buttonTranslationKeyTypes */ public function indexAction_SetToggleRemovedVehiclesActionTitle_WithRelevantMessage_WhenQueryParamIsSet_AndLicenceHasRemovedVehicles(string $type) @@ -568,7 +611,7 @@ public function indexAction_SetToggleRemovedVehiclesActionTitle_WithRelevantMess $request = $this->setUpRequest('/'); $request->setQuery($this->parametersWhichIncludeRemoved()); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, 'results' => []]); $expectedKey = sprintf('toggleRemovedVehiclesAction%s', ucfirst($type)); $expectedTitle = sprintf('licence.vehicle.list.section.removed.action.hide-removed-vehicles.%s', $type); @@ -584,7 +627,6 @@ public function indexAction_SetToggleRemovedVehiclesActionTitle_WithRelevantMess /** * @param string $type * @test - * @depends indexAction_SetShowRemovedVehiclesToTrue_WhenALicenceHasOneRemovedVehicle * @dataProvider buttonTranslationKeyTypes */ public function indexAction_DoesNotSetToggleRemovedVehiclesActionTitle_WhenQueryParamIsNotSet_AndLicenceDoesNotHaveRemovedVehicles(string $type) @@ -594,7 +636,7 @@ public function indexAction_DoesNotSetToggleRemovedVehiclesActionTitle_WhenQuery $request = $this->setUpRequest('/'); $request->setQuery($this->parametersWhichIncludeRemoved()); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 0, 'results' => []]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 0, 'results' => []]); $expectedKey = sprintf('toggleRemovedVehiclesAction%s', ucfirst($type)); // Execute @@ -654,10 +696,10 @@ public function indexAction_ValidatesInput_WhenInvalid_ReturnsRedirectResponse(a $this->setUpSut(); $request = $this->setUpRequest('foobarbaz', $input); $routeMatch = new RouteMatch(['licence' => 1]); - // Define Expectations - $redirectHelper = $this->resolveMockService($this->serviceManager, Redirect::class); - $redirectHelper->shouldReceive('refresh')->withNoArgs()->andReturn($expectedResponse = new Response())->once(); + $this->flashMessengerMock->shouldReceive('addErrorMessage')->withAnyArgs()->once(); + // Define Expectations + $this->redirectHelperMock->shouldReceive('refresh')->withNoArgs()->andReturn($expectedResponse = new Response())->once(); // Execute $response = $this->sut->indexAction($request, $routeMatch); @@ -679,10 +721,10 @@ public function indexAction_ValidatesInput_WhenInvalid_FlashesValidationMessages $this->setUpSut(); $request = $this->setUpRequest('foobarbaz', $input); $routeMatch = new RouteMatch(['licence' => 8]); - $flashMessenger = $this->resolveMockService($this->serviceManager, FlashMessengerHelperService::class); // Define Expectations - $flashMessenger->shouldReceive('addErrorMessage')->with($expectedFlashMessage)->once(); + $this->flashMessengerMock->shouldReceive('addErrorMessage')->with($expectedFlashMessage)->once(); + $this->redirectHelperMock->shouldReceive('refresh')->withNoArgs()->andReturn($expectedResponse = new Response())->once(); // Execute $this->sut->indexAction($request, $routeMatch); @@ -701,12 +743,12 @@ public function indexAction_ValidatesInput_WhenInvalid_TranslatesValidationMessa $this->setUpSut(); $request = $this->setUpRequest('foobarbaz', $input); $routeMatch = new RouteMatch(['licence' => 8]); - $translator = $this->resolveMockService($this->serviceManager, TranslationHelperService::class); - $baseTranslator = $translator->getTranslator(); + $baseTranslator = $this->translatorMock->getTranslator(); // Define Expectations $baseTranslator->shouldReceive('translate')->with($expectedFlashMessage, IsAnything::anything())->atLeast()->once()->andReturn(''); - + $this->redirectHelperMock->shouldReceive('refresh')->withNoArgs()->andReturn($expectedResponse = new Response())->once(); + $this->flashMessengerMock->shouldReceive('addErrorMessage')->withAnyArgs()->once(); // Execute $this->sut->indexAction($request, $routeMatch); } @@ -741,10 +783,9 @@ public function indexAction_ReturnsRemovedVehiclesTable_ExcludingActiveVehicles( $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); // Define Expectations - $queryHandler->shouldReceive('__invoke')->withArgs(function ($query) { + $this->queryHandlerMock->shouldReceive('__invoke')->withArgs(function ($query) { return $query instanceof Vehicles && $query->getIncludeActive() === false; })->once()->andReturns($this->setUpQueryResponse()); @@ -761,10 +802,9 @@ public function indexAction_ReturnsRemovedVehiclesTable_SortedByDefault() $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); // Define Expectations - $queryHandler->shouldReceive('__invoke')->withArgs(function ($query) { + $this->queryHandlerMock->shouldReceive('__invoke')->withArgs(function ($query) { return $query instanceof Vehicles && $query->getIncludeRemoved() === true && $query->getSort() === 'removalDate'; })->once()->andReturns($this->setUpQueryResponse()); @@ -781,10 +821,9 @@ public function indexAction_ReturnsRemovedVehiclesTable_OrderedByDefault() $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); // Define Expectations - $queryHandler->shouldReceive('__invoke')->withArgs(function ($query) { + $this->queryHandlerMock->shouldReceive('__invoke')->withArgs(function ($query) { return $query instanceof Vehicles && $query->getIncludeRemoved() === true && $query->getOrder() === 'DESC'; })->once()->andReturns($this->setUpQueryResponse()); @@ -801,10 +840,9 @@ public function indexAction_ReturnsRemovedVehiclesTable_LimitsTo10ByDefault() $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); // Define Expectations - $queryHandler->shouldReceive('__invoke')->withArgs(function ($query) { + $this->queryHandlerMock->shouldReceive('__invoke')->withArgs(function ($query) { return $query instanceof Vehicles && $query->getIncludeRemoved() === true && $query->getLimit() === 10; })->once()->andReturns($this->setUpQueryResponse()); @@ -821,10 +859,9 @@ public function indexAction_ReturnsRemovedVehiclesTable_SetsPageToFirstPageByDef $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); // Define Expectations - $queryHandler->shouldReceive('__invoke')->withArgs(function ($query) { + $this->queryHandlerMock->shouldReceive('__invoke')->withArgs(function ($query) { return $query instanceof Vehicles && $query->getIncludeRemoved() === true && $query->getPage() === 1; })->once()->andReturns($this->setUpQueryResponse()); @@ -833,7 +870,6 @@ public function indexAction_ReturnsRemovedVehiclesTable_SetsPageToFirstPageByDef } /** - * @depends postAction_IsCallable * @test */ public function postAction_RespondsInHtmlFormat_SetsUserOCRSOptInPreference_CheckboxValidValuesRunsCommand() @@ -842,14 +878,12 @@ public function postAction_RespondsInHtmlFormat_SetsUserOCRSOptInPreference_Chec $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $commandHandler = $this->resolveMockService($this->serviceManager, HandleCommand::class); - $formHelper = $this->resolveMockService($this->serviceManager, FormHelperService::class); $mockForm = $this->setUpForm(); $mockForm->shouldReceive('getData')->andReturn(['ocrsCheckbox' => $expected = 'Y']); - $formHelper->shouldReceive('createForm')->andReturn($mockForm); + $this->formHelperMock->shouldReceive('createForm')->andReturn($mockForm); // Define Expectations - $commandHandler + $this->commandHandlerMock ->shouldReceive('__invoke') ->withArgs(function ($command) use ($expected) { return $command instanceof UpdateVehicles && $command->getShareInfo() === $expected; @@ -862,7 +896,6 @@ public function postAction_RespondsInHtmlFormat_SetsUserOCRSOptInPreference_Chec } /** - * @depends postAction_IsCallable * @test */ public function postAction_RespondsInHtmlFormat_SetsUserOCRSOptInPreference_CheckboxInvalidValues_ReturnsIndexActionWithErrors() @@ -871,15 +904,13 @@ public function postAction_RespondsInHtmlFormat_SetsUserOCRSOptInPreference_Chec $this->setUpSut(); $request = $this->setUpRequest('/'); $routeMatch = new RouteMatch([]); - $commandHandler = $this->resolveMockService($this->serviceManager, HandleCommand::class); - $formHelper = $this->resolveMockService($this->serviceManager, FormHelperService::class); $mockForm = $this->setUpForm(); $mockForm->shouldReceive('isValid')->andReturnFalse(); - $formHelper->shouldReceive('createForm')->andReturn($mockForm); + $this->formHelperMock->shouldReceive('createForm')->andReturn($mockForm); // Define Expectations $updateVehicleCommandMatcher = IsInstanceOf::anInstanceOf(UpdateVehicles::class); - $commandHandler->shouldReceive('__invoke')->with($updateVehicleCommandMatcher)->never(); + $this->commandHandlerMock->shouldReceive('__invoke')->with($updateVehicleCommandMatcher)->never(); // Execute $this->sut->postAction($request, $routeMatch); @@ -895,7 +926,7 @@ public function indexAction_HidesRemovedVehicles_WhenSearching_AndLicenceHasRemo $request = $this->setUpRequest('/foo/bar'); $request->setQuery(new Parameters([ListVehicleSearch::FIELD_VEHICLE_SEARCH => [AbstractInputSearch::ELEMENT_INPUT_NAME => 'foo']])); $routeMatch = new RouteMatch([]); - $this->injectRemovedVehiclesQueryResultData($this->serviceManager, ['count' => 1, ['results' => []]]); + $this->injectRemovedVehiclesQueryResultData($this->serviceLocatorMock, ['count' => 1, ['results' => []]]); // Execute $result = (array) $this->sut->indexAction($request, $routeMatch)->getVariables(); @@ -906,43 +937,51 @@ public function indexAction_HidesRemovedVehicles_WhenSearching_AndLicenceHasRemo protected function setUp(): void { - $this->setUpServiceManager(); + $this->commandHandlerMock = m::mock(HandleCommand::class); + $this->queryHandlerMock = m::mock(HandleQuery::class); + $this->translatorMock = m::mock(TranslationHelperService::class); + $this->urlHelperMock = m::mock(Url::class); + $this->responseHelperMock = m::mock(ResponseHelperService::class); + $this->tableFactoryMock = m::mock(TableFactory::class); + $this->formHelperMock = m::mock(FormHelperService::class); + $this->flashMessengerMock = m::mock(FlashMessengerHelperService::class); + $this->redirectHelperMock = m::mock(Redirect::class); + $this->serviceLocatorMock = m::mock(ServiceLocatorInterface::class); } - public function setUpDefaultServices() + protected function setUpSut() { - $this->serviceManager->setService(TableFactory::class, $this->setUpTableFactory()); - $this->serviceManager->setService(TranslationHelperService::class, $this->setUpTranslator()); - $this->serviceManager->setService(ResponseHelperService::class, $this->setUpResponseHelper()); - $this->serviceManager->setService(FormHelperService::class, $this->setUpFormHelper()); - $this->serviceManager->setService(FlashMessengerHelperService::class, $this->setUpFlashMessenger()); - $this->serviceManager->setService(HandleCommand::class, $this->setUpCommandHandler()); - $this->serviceManager->setService(HandleQuery::class, $this->setUpQueryHandler()); + $this->setUpTranslator(); + $this->setUpQueryHandler(); + $this->setUpTableFactory(); + $this->setUpFormHelper(); $this->urlHelper(); - $this->serviceManager->setService(Redirect::class, $this->setUpRedirectHelper()); - } - protected function setUpSut() - { - $factory = new ListVehicleControllerFactory(); - $dispatcher = $factory->__invoke($this->serviceManager, ListVehicleController::class); - $this->sut = $dispatcher->getDelegate(); + $this->sut = new ListVehicleController( + $this->commandHandlerMock, + $this->queryHandlerMock, + $this->translatorMock, + $this->urlHelperMock, + $this->responseHelperMock, + $this->tableFactoryMock, + $this->formHelperMock, + $this->flashMessengerMock, + $this->redirectHelperMock + ); } /** - * @return HandleQuery */ - protected function setUpQueryHandler(): HandleQuery + protected function setUpQueryHandler() { $instance = m::mock(HandleQuery::class); - $instance->shouldIgnoreMissing(); - $instance->shouldReceive('__invoke')->andReturn($this->setUpQueryResponse())->byDefault(); - $instance->shouldReceive('__invoke')->with(IsInstanceOf::anInstanceOf(Licence::class))->andReturnUsing(function ($query) { + $this->queryHandlerMock->shouldIgnoreMissing(); + $this->queryHandlerMock->shouldReceive('__invoke')->andReturn($this->setUpQueryResponse())->byDefault(); + $this->queryHandlerMock->shouldReceive('__invoke')->with(IsInstanceOf::anInstanceOf(Licence::class))->andReturnUsing(function ($query) { $licenceData = $this->setUpDefaultLicenceData(); $licenceData['id'] = $query->getId(); return $this->setUpQueryResponse($licenceData); })->byDefault(); - return $instance; } /** @@ -974,17 +1013,14 @@ protected function setUpCommandHandler(): HandleCommand return $instance; } - /** - * @return TableFactory - */ - protected function setUpTableFactory(): TableFactory + + protected function setUpTableFactory() { $instance = m::mock(TableFactory::class); - $instance->shouldIgnoreMissing(); - $instance->shouldReceive('prepareTable', 'getTableBuilder')->andReturnUsing(function () { + $this->tableFactoryMock->shouldIgnoreMissing(); + $this->tableFactoryMock->shouldReceive('prepareTable', 'getTableBuilder')->andReturnUsing(function () { return $this->setUpTableBuilder(); })->byDefault(); - return $instance; } /** @@ -1012,17 +1048,13 @@ public function setUpTableBuilder(): MockInterface return $tableBuilder; } - /** - * @return MockInterface - */ - protected function setUpTranslator(): MockInterface + protected function setUpTranslator() { - $instance = m::mock(TranslationHelperService::class); - $instance->shouldIgnoreMissing(''); - $instance->shouldReceive('translate')->andReturnUsing(function ($val) { + $this->translatorMock->shouldIgnoreMissing(''); + $this->translatorMock->shouldReceive('translate')->andReturnUsing(function ($val) { return $val; })->byDefault(); - $instance->shouldReceive('translateReplace')->andReturnUsing(function ($message, $params) { + $this->translatorMock->shouldReceive('translateReplace')->andReturnUsing(function ($message, $params) { return $message . ':' . json_encode($params); })->byDefault(); @@ -1030,22 +1062,13 @@ protected function setUpTranslator(): MockInterface $baseTranslator->shouldReceive('translate')->andReturnUsing(function ($val) { return $val; })->byDefault(); - $instance->shouldReceive('getTranslator')->andReturn($baseTranslator)->byDefault(); - - return $instance; + $this->translatorMock->shouldReceive('getTranslator')->andReturn($baseTranslator)->byDefault(); } - /** - * @return MockInterface|Url - */ - protected function urlHelper(): MockInterface + + protected function urlHelper() { - if (! $this->serviceManager->has(Url::class)) { - $instance = m::mock(Url::class); - $instance->shouldIgnoreMissing(''); - $this->serviceManager->setService(Url::class, $instance); - } - return $this->serviceManager->get(Url::class); + $this->urlHelperMock->shouldIgnoreMissing(''); } /** @@ -1058,24 +1081,17 @@ protected function setUpResponseHelper(): ResponseHelperService return $instance; } - /** - * @return FormHelperService - */ - protected function setUpFormHelper(): FormHelperService + protected function setUpFormHelper() { - $instance = m::mock(FormHelperService::class); - $instance->shouldIgnoreMissing(); + $this->formHelperMock->shouldIgnoreMissing(); $mockForm = $this->setUpForm(); - $instance->shouldReceive('createForm')->andReturn($mockForm)->byDefault(); + $this->formHelperMock->shouldReceive('createForm')->andReturn($mockForm)->byDefault(); // Mock search form by default $searchForm = $this->setUpForm(); $any = IsAnything::anything(); - $instance->shouldReceive('createForm')->with(ListVehicleSearch::class, $any, $any)->andReturn($searchForm)->byDefault(); - - - return $instance; + $this->formHelperMock->shouldReceive('createForm')->with(ListVehicleSearch::class, $any, $any)->andReturn($searchForm)->byDefault(); } /** @@ -1106,8 +1122,7 @@ protected function expectTableToBePrepared(ServiceLocatorInterface $serviceLocat { $any = IsAnything::anything(); $tableBuilder = $this->setUpTableBuilder(); - $tableFactory = $this->resolveMockService($serviceLocator, TableFactory::class); - $tableFactory->shouldReceive('prepareTable')->with($tableName, $data ?? $any, $params ?? $any)->once()->andReturn($tableBuilder); + $this->tableFactoryMock->shouldReceive('prepareTable')->with($tableName, $data ?? $any, $params ?? $any)->once()->andReturn($tableBuilder); return $tableBuilder; } @@ -1156,8 +1171,7 @@ protected function setUpRedirectHelper(): MockInterface protected function injectRemovedVehiclesQueryResultData(ServiceLocatorInterface $serviceLocator, array $queryResultData) { $removedVehiclesQueryResponse = $this->setUpQueryResponse($queryResultData); - $queryHandler = $this->resolveMockService($serviceLocator, HandleQuery::class); - $queryHandler->shouldReceive('__invoke')->withArgs(function ($query) { + $this->queryHandlerMock->shouldReceive('__invoke')->withArgs(function ($query) { return $query instanceof Vehicles && $query->getIncludeActive() === false; })->andReturns($removedVehiclesQueryResponse)->byDefault(); } diff --git a/test/Olcs/src/Controller/Licence/Vehicle/SwitchBoardControllerTest.php b/test/Olcs/src/Controller/Licence/Vehicle/SwitchBoardControllerTest.php index 52b1b5346..6fbe37fd1 100644 --- a/test/Olcs/src/Controller/Licence/Vehicle/SwitchBoardControllerTest.php +++ b/test/Olcs/src/Controller/Licence/Vehicle/SwitchBoardControllerTest.php @@ -11,31 +11,68 @@ use Common\Service\Cqrs\Response as QueryResponse; use Common\Service\Helper\FormHelperService; use Common\Service\Helper\ResponseHelperService; -use Common\Test\MockeryTestCase; -use Common\Test\MocksServicesTrait; use Common\View\Helper\Panel; use Dvsa\Olcs\Transfer\Query\Licence\Licence; use Hamcrest\Core\IsInstanceOf; +use Interop\Container\Containerinterface; use Laminas\Form\Annotation\AnnotationBuilder; use Laminas\Http\Request; use Laminas\Http\Response; +use Laminas\Mvc\Controller\PluginManager; use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger; use Laminas\Mvc\Controller\Plugin\Url; use Laminas\Router\Http\RouteMatch; -use Laminas\ServiceManager\ServiceManager; use Laminas\Stdlib\Parameters; use Laminas\View\Model\ViewModel; use Mockery as m; +use Mockery\Adapter\Phpunit\MockeryTestCase; use Mockery\MockInterface; use Olcs\Controller\Licence\Vehicle\ListVehicleController; use Olcs\Controller\Licence\Vehicle\SwitchBoardController; -use Olcs\Controller\Licence\Vehicle\SwitchBoardControllerFactory; use Olcs\Form\Model\Form\Vehicle\SwitchBoard; use Olcs\Session\LicenceVehicleManagement; class SwitchBoardControllerTest extends MockeryTestCase { - use MocksServicesTrait; + /** + * @var FlashMessenger + */ + private $flashMessengerMock; + + /** + * @var FormHelperService + */ + private $formHelperMock; + + /** + * @var HandleQuery + */ + private $queryHandlerMock; + + /** + * @var Redirect + */ + private $redirectHelperMock; + + /** + * @var ResponseHelperService + */ + private $responseHelperMock; + + /** + * @var LicenceVehicleManagement + */ + private $sessionMock; + + /** + * @var Url + */ + private $urlHelperMock; + + /** + * @var FormValidator + */ + private $formValidatorMock; protected const VEHICLES_ROUTE = ['lva-licence/vehicles', [], [], true]; protected const A_DECISION_VALUE = 'A_DECISION_VALUE'; @@ -56,14 +93,16 @@ public function indexAction_IsCallable() /** * @test - * @depends indexAction_IsCallable */ public function indexAction_ReturnsViewModel() { // Setup $this->setUpSut(); $routeMatch = new RouteMatch([]); - + // Define Expectations + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); // Execute $result = $this->sut->indexAction(new Request(), $routeMatch); @@ -73,7 +112,6 @@ public function indexAction_ReturnsViewModel() /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_ReturnsViewModel_WithPanel_WhenFlashMessageHasPanelNamespace() { @@ -82,8 +120,9 @@ public function indexAction_ReturnsViewModel_WithPanel_WhenFlashMessageHasPanelN $routeMatch = new RouteMatch([]); // Define Expectations - $flashMessenger = $this->resolveMockService($this->serviceManager, FlashMessenger::class); - $flashMessenger->shouldReceive('getMessages') + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages') ->with('panel') ->andReturn(['title']); @@ -101,7 +140,6 @@ public function indexAction_ReturnsViewModel_WithPanel_WhenFlashMessageHasPanelN /** * @test - * @depends indexAction_ReturnsViewModel_WithPanel_WhenFlashMessageHasPanelNamespace */ public function indexAction_ReturnsViewModel_WithPanelBody_WhenFlashMessageHasPanelNamespaceSecondMessage() { @@ -110,8 +148,9 @@ public function indexAction_ReturnsViewModel_WithPanelBody_WhenFlashMessageHasPa $routeMatch = new RouteMatch([]); // Define Expectations - $flashMessenger = $this->resolveMockService($this->serviceManager, FlashMessenger::class); - $flashMessenger->shouldReceive('getMessages') + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages') ->with('panel') ->andReturn(['title', 'body']); @@ -130,7 +169,6 @@ public function indexAction_ReturnsViewModel_WithPanelBody_WhenFlashMessageHasPa /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_ReturnsViewModel_WithBackRouteToLicenceOverview() { @@ -140,8 +178,9 @@ public function indexAction_ReturnsViewModel_WithBackRouteToLicenceOverview() $expectedUrl = 'licence/overview/link'; // Define Expectations - $urlHelper = $this->resolveMockService($this->serviceManager, Url::class); - $urlHelper->shouldReceive('fromRoute') + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute') ->with(SwitchBoardController::ROUTE_LICENCE_OVERVIEW, [], [], true) ->andReturn($expectedUrl); @@ -154,7 +193,6 @@ public function indexAction_ReturnsViewModel_WithBackRouteToLicenceOverview() /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_ReturnsViewModel_WithSwitchBoardForm() { @@ -162,16 +200,18 @@ public function indexAction_ReturnsViewModel_WithSwitchBoardForm() $this->setUpSut(); $routeMatch = new RouteMatch([]); + // Define Expectations + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); // Execute $result = $this->sut->indexAction(new Request(), $routeMatch); - // Assert $this->assertInstanceOf(Form::class, $result->getVariable('form')); } /** * @test - * @depends indexAction_ReturnsViewModel_WithSwitchBoardForm */ public function indexAction_SwitchBoardOnlyHasAdd_WhenLicenceHasNoVehicles() { @@ -180,12 +220,14 @@ public function indexAction_SwitchBoardOnlyHasAdd_WhenLicenceHasNoVehicles() $routeMatch = new RouteMatch([]); // Define expectations + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); $licenceData = $this->setUpDefaultLicenceData(); $licenceData['activeVehicleCount'] = 0; $licenceData['totalVehicleCount'] = 0; - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); - $queryHandler->shouldReceive('__invoke') + $this->queryHandlerMock->shouldReceive('__invoke') ->with(IsInstanceOf::anInstanceOf(Licence::class)) ->andReturn($this->setUpQueryResponse($licenceData)); @@ -205,7 +247,6 @@ public function indexAction_SwitchBoardOnlyHasAdd_WhenLicenceHasNoVehicles() /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_SwitchBoardRemovesTransferOption_WhenLicenceIsNotMLH() { @@ -214,11 +255,13 @@ public function indexAction_SwitchBoardRemovesTransferOption_WhenLicenceIsNotMLH $routeMatch = new RouteMatch([]); // Define expectations + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); $licenceData = $this->setUpDefaultLicenceData(); $licenceData['isMlh'] = false; - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); - $queryHandler->shouldReceive('__invoke') + $this->queryHandlerMock->shouldReceive('__invoke') ->with(IsInstanceOf::anInstanceOf(Licence::class)) ->andReturn($this->setUpQueryResponse($licenceData)); @@ -234,7 +277,6 @@ public function indexAction_SwitchBoardRemovesTransferOption_WhenLicenceIsNotMLH /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_SwitchBoardRemovesViewOptionButKeepsViewRemoved_WhenAllVehiclesHaveBeenRemoved() { @@ -243,12 +285,14 @@ public function indexAction_SwitchBoardRemovesViewOptionButKeepsViewRemoved_When $routeMatch = new RouteMatch([]); // Define expectations + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); $licenceData = $this->setUpDefaultLicenceData(); $licenceData['activeVehicleCount'] = 0; $licenceData['totalVehicleCount'] = 1; - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); - $queryHandler->shouldReceive('__invoke') + $this->queryHandlerMock->shouldReceive('__invoke') ->with(IsInstanceOf::anInstanceOf(Licence::class)) ->andReturn($this->setUpQueryResponse($licenceData)); @@ -264,7 +308,6 @@ public function indexAction_SwitchBoardRemovesViewOptionButKeepsViewRemoved_When /** * @test - * @depends indexAction_ReturnsViewModel */ public function indexAction_SwitchBoardHasViewOptionRemovesViewRemoved_WhenNoVehiclesHaveBeenRemoved() { @@ -273,12 +316,14 @@ public function indexAction_SwitchBoardHasViewOptionRemovesViewRemoved_WhenNoVeh $routeMatch = new RouteMatch([]); // Define expectations + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); + $this->urlHelperMock->shouldReceive('fromRoute')->withAnyArgs(); $licenceData = $this->setUpDefaultLicenceData(); $licenceData['activeVehicleCount'] = 1; $licenceData['totalVehicleCount'] = 1; - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); - $queryHandler->shouldReceive('__invoke') + $this->queryHandlerMock->shouldReceive('__invoke') ->with(IsInstanceOf::anInstanceOf(Licence::class)) ->andReturn($this->setUpQueryResponse($licenceData)); @@ -294,13 +339,12 @@ public function indexAction_SwitchBoardHasViewOptionRemovesViewRemoved_WhenNoVeh /** * @test - * @depends indexAction_IsCallable */ public function indexAction_WithPost_ShouldReturnRedirectToIndexAction_WhenFormIsInvalid() { // Setup $this->setUpSut(); - $this->formValidator()->allows('isValid')->andReturnUsing(function($form) { + $this->formValidatorMock->allows('isValid')->andReturnUsing(function ($form) { $form->isValid(); return false; }); @@ -308,9 +352,14 @@ public function indexAction_WithPost_ShouldReturnRedirectToIndexAction_WhenFormI $request = $this->setUpDecisionRequest(static::A_DECISION_VALUE); $routeMatch = new RouteMatch([]); + // Define expectations + $this->flashMessengerMock->shouldReceive('hasMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('addMessage')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('addMessages')->withAnyArgs(); + $this->flashMessengerMock->shouldReceive('getMessages')->withAnyArgs(); // Expect - $this->redirectHelper()->expects('toRoute')->with(...static::VEHICLES_ROUTE)->andReturn($expectedResponse); + $this->redirectHelperMock->expects('toRoute')->with(...static::VEHICLES_ROUTE)->andReturn($expectedResponse); // Execute $result = $this->sut->indexAction($request, $routeMatch); @@ -321,8 +370,6 @@ public function indexAction_WithPost_ShouldReturnRedirectToIndexAction_WhenFormI /** * @test - * @depends indexAction_IsCallable - * @depends indexAction_ReturnsViewModel * @dataProvider indexAction_WithPost_ShouldRedirectToPage_DependantOnDecision_Provider */ public function indexAction_WithPost_ShouldRedirectToPage_DependantOnDecision(string $request, int $activeVehicleCount, array $route) @@ -332,8 +379,7 @@ public function indexAction_WithPost_ShouldRedirectToPage_DependantOnDecision(st $routeMatch = new RouteMatch([]); // Define expectations - $redirectHelper = $this->resolveMockService($this->serviceManager, Redirect::class); - $redirectHelper->expects('toRoute') + $this->redirectHelperMock->expects('toRoute') ->withArgs($route) ->andReturn($expectedResponse = new Response()); @@ -342,8 +388,7 @@ public function indexAction_WithPost_ShouldRedirectToPage_DependantOnDecision(st $licenceData['activeVehicleCount'] = $activeVehicleCount; $licenceData['totalVehicleCount'] = 1; - $queryHandler = $this->resolveMockService($this->serviceManager, HandleQuery::class); - $queryHandler->shouldReceive('__invoke') + $this->queryHandlerMock->shouldReceive('__invoke') ->with(IsInstanceOf::anInstanceOf(Licence::class)) ->andReturn($this->setUpQueryResponse($licenceData)); @@ -427,77 +472,49 @@ public function indexAction_WithPost_ShouldRedirectToPage_DependantOnDecision_Pr protected function setUp(): void { - $this->setUpServiceManager(); + $this->flashMessengerMock = m::mock(FlashMessenger::class); + $this->formHelperMock = m::mock(FormHelperService::class); + $this->queryHandlerMock = m::mock(HandleQuery::class); + $this->redirectHelperMock = m::mock(Redirect::class); + $this->responseHelperMock = m::mock(ResponseHelperService::class); + $this->sessionMock = new LicenceVehicleManagement(); + $this->urlHelperMock = m::mock(Url::class); + $this->formValidatorMock = m::mock(FormValidator::class); } - /** - * @inheritDoc - */ - protected function setUpDefaultServices(ServiceManager $serviceManager) + protected function setUpSut() { - $this->serviceManager->setService(FlashMessenger::class, $this->setUpMockService(FlashMessenger::class)); - $this->serviceManager->setService(FormHelperService::class, $this->formHelper()); - $this->serviceManager->setService(HandleQuery::class, $this->setupQueryHandler()); - $this->serviceManager->setService(ResponseHelperService::class, $this->setUpMockService(ResponseHelperService::class)); - $this->serviceManager->setService(Url::class, $this->setUpMockService(Url::class)); - $this->serviceManager->setService(LicenceVehicleManagement::class, new LicenceVehicleManagement()); - $this->redirectHelper(); + // Create a mock container (similar to a service manager) + $this->formHelper(); + $this->setupQueryHandler(); $this->formValidator(); - } - - /** - * @return SwitchBoardController - */ - protected function setUpSut(): SwitchBoardController - { - $this->sut = (new SwitchBoardControllerFactory())->__invoke($this->serviceManager, SwitchBoardController::class)->getDelegate(); - return $this->sut; - } - /** - * @return MockInterface|Redirect - */ - protected function redirectHelper(): MockInterface - { - if (! $this->serviceManager->has(Redirect::class)) { - $instance = $this->setUpMockService(Redirect::class); - $this->serviceManager->setService(Redirect::class, $instance); - } - return $this->serviceManager->get(Redirect::class); + $this->sut = new SwitchBoardController( + $this->flashMessengerMock, + $this->formHelperMock, + $this->queryHandlerMock, + $this->redirectHelperMock, + $this->responseHelperMock, + $this->sessionMock, + $this->urlHelperMock, + $this->formValidatorMock + ); } - /** - * @return MockInterface|FormValidator - */ - protected function formValidator(): MockInterface + protected function formValidator() { - if (! $this->serviceManager->has(FormValidator::class)) { - $instance = $this->setUpMockService(FormValidator::class); - $instance->allows('isValid')->andReturnUsing(function ($form) { - - $form->isValid(); - return true; - })->byDefault(); - $this->serviceManager->setService(FormValidator::class, $instance); - } - return $this->serviceManager->get(FormValidator::class); + $this->formValidatorMock->allows('isValid')->andReturnUsing(function ($form) { + $form->isValid(); + return true; + })->byDefault(); } - /** - * @return MockInterface|FormHelperService - */ - protected function formHelper(): MockInterface + protected function formHelper() { - if (! $this->serviceManager->has(FormHelperService::class)) { - $instance = $this->setUpMockService(FormHelperService::class); - $instance->shouldReceive('createForm')->andReturnUsing(function () { - $annotationBuilder = new AnnotationBuilder(); - $form = $annotationBuilder->createForm(SwitchBoard::class); - return $form; - })->byDefault(); - $this->serviceManager->setService(FormHelperService::class, $instance); - } - return $this->serviceManager->get(FormHelperService::class); + $this->formHelperMock->shouldReceive('createForm')->andReturnUsing(function () { + $annotationBuilder = new AnnotationBuilder(); + return $annotationBuilder->createForm(SwitchBoard::class); + })->byDefault(); } /** @@ -514,13 +531,9 @@ protected function setUpDefaultLicenceData(): array ]; } - /** - * @return HandleQuery|m\LegacyMockInterface|MockInterface - */ protected function setupQueryHandler() { - $instance = m::mock(HandleQuery::class); - $instance->shouldReceive('__invoke') + $this->queryHandlerMock->shouldReceive('__invoke') ->with(IsInstanceOf::anInstanceOf(Licence::class)) ->andReturnUsing(function () { return $this->setUpQueryResponse( @@ -528,7 +541,6 @@ protected function setupQueryHandler() ); }) ->byDefault(); - return $instance; } /** @@ -551,9 +563,9 @@ protected function setUpDecisionRequest(string $value): Request $request->setMethod(Request::METHOD_POST); $request->setPost( new Parameters([ - SwitchBoard::FIELD_OPTIONS_FIELDSET_NAME => [ - SwitchBoard::FIELD_OPTIONS_NAME => $value - ] + SwitchBoard::FIELD_OPTIONS_FIELDSET_NAME => [ + SwitchBoard::FIELD_OPTIONS_NAME => $value + ] ]) ); return $request; diff --git a/test/Olcs/src/Controller/SessionTimeoutControllerTest.php b/test/Olcs/src/Controller/SessionTimeoutControllerTest.php index d91ba294a..a0478a1b4 100644 --- a/test/Olcs/src/Controller/SessionTimeoutControllerTest.php +++ b/test/Olcs/src/Controller/SessionTimeoutControllerTest.php @@ -1,28 +1,24 @@ serviceManager, 'Expected service manager to be set. Hint: You may need to call `setUpServiceManager` before trying to get a service manager'); - return $this->serviceManager; - } + private IdentityProviderInterface $identityProviderMock; + protected Redirect $redirectHelperMock; + protected SessionTimeoutController $sut; /** * @test */ public function indexAction_IsCallable() { - // Setup - $serviceLocator = $this->setUpServiceManager(); - - $sut = $this->setUpSut($serviceLocator, new Request()); - + $this->setUpSut(); // Assert - $this->assertTrue(method_exists($sut, 'indexAction') && is_callable([$sut, 'indexAction'])); - } - - /** - * @return ServiceManager - */ - protected function setUpServiceManager(): ServiceManager - { - $this->serviceManager = new ServiceManager(); - $this->serviceManager->setAllowOverride(true); - $services = $this->setUpDefaultServices($this->serviceManager); - - // Maintain support for deprecated way of registering services via an array of services. Instead, services - // should be registered by calling the available setter methods on the ServiceManager instance. - if (is_array($services)) { - foreach ($services as $serviceName => $service) { - $this->serviceManager->setService($serviceName, $service); - } - } - - // Set controller plugin manager to the main service manager so that all services can be resolved from the one - // service manager instance. - $this->serviceManager->setService('ControllerPluginManager', $this->serviceManager); - - return $this->serviceManager; + $this->assertTrue(method_exists($this->sut, 'indexAction') && is_callable([$this->sut, 'indexAction'])); } /** * @test - * @depends indexAction_IsCallable */ public function indexAction_ReturnsViewModelIfIdentityIsAnonymous() { - // Setup - $serviceLocator = $this->setUpServiceLocator(); - $sut = $this->setUpSut($serviceLocator, new Request()); - + $this->setUpSut(); // Define Expectations - $identity = $this->setUpMockService(User::class); + $identity = m::mock(User::class); $identity->shouldReceive('isAnonymous')->andReturnTrue(); - $currentUser = $this->resolveMockService($serviceLocator, IdentityProviderInterface::class); - $currentUser->shouldReceive('getIdentity')->withNoArgs()->andReturn($identity); + $this->identityProviderMock->shouldReceive('getIdentity')->withNoArgs()->andReturn($identity); // Execute - $result = $sut->indexAction($this->setUpRequest()); + $result = $this->sut->indexAction($this->setUpRequest()); // Assert $this->assertInstanceOf(ViewModel::class, $result); @@ -113,41 +62,39 @@ public function indexAction_ReturnsViewModelIfIdentityIsAnonymous() /** * @test - * @depends indexAction_ReturnsViewModelIfIdentityIsAnonymous */ public function indexAction_ReturnsViewModelIfIdentityIsNull() { - // Setup - $serviceLocator = $this->setUpServiceLocator(); - $sut = $this->setUpSut($serviceLocator, new Request()); - + $this->setUpSut(); // Define Expectations - $currentUser = $this->resolveMockService($serviceLocator, IdentityProviderInterface::class); - $currentUser->shouldReceive('getIdentity')->withNoArgs()->andReturnNull()->once(); + $this->identityProviderMock->shouldReceive('getIdentity')->withNoArgs()->andReturnNull()->once(); // Execute - $result = $sut->indexAction($this->setUpRequest()); + $result = $this->sut->indexAction($this->setUpRequest()); // Assert $this->assertInstanceOf(ViewModel::class, $result); } - /** * @test - * @depends indexAction_ReturnsViewModelIfIdentityIsNull */ public function indexAction_LogsOutUserIfLoggedIn() { - // Setup - $serviceLocator = $this->setUpServiceLocator(); + $this->setUpSut(); + //setup $request = $this->setUpRequest(); - $sut = $this->setUpSut($serviceLocator, new Request()); - $this->setUpIdentityWithClearSession($this->identityProviderClass); + //Define Expectation + $this->redirectHelperMock->shouldReceive('refresh') + ->withNoArgs() + ->andReturn($expectedResponse = new Response()) + ->once(); + + $this->setUpIdentityWithClearSession(); // Execute - $response = $sut->indexAction($request); + $response = $this->sut->indexAction($request); // Assert $this->assertInstanceOf(Response::class, $response); @@ -155,27 +102,24 @@ public function indexAction_LogsOutUserIfLoggedIn() /** * @test - * @depends indexAction_LogsOutUserIfLoggedIn * @dataProvider dpIdentityProviderClass */ public function indexAction_RedirectsUserIfLoggedIn(string $identityProviderClass) { + $this->setUpSut(); // Setup - $serviceLocator = $this->setUpServiceLocator(); $request = $this->setUpRequest(); - $sut = $this->setUpSut($serviceLocator, new Request()); - $this->setUpIdentityWithClearSession($identityProviderClass); + $this->setUpIdentityWithClearSession(); // Define Expectations - $redirectHelper = $this->resolveMockService($serviceLocator, Redirect::class); - $redirectHelper->shouldReceive('refresh') + $this->redirectHelperMock->shouldReceive('refresh') ->withNoArgs() ->andReturn($expectedResponse = new Response()) ->once(); // Execute - $response = $sut->indexAction($request); + $response = $this->sut->indexAction($request); // Assert $this->assertSame($expectedResponse, $response); @@ -189,63 +133,23 @@ public function dpIdentityProviderClass(): array ]; } - /** - * " - * @param ServiceLocatorInterface $serviceLocator - * @return array - */ - protected function setUpDefaultServices(ServiceLocatorInterface $serviceLocator): array - { - return [ - IdentityProviderInterface::class => $this->setUpIdentity($this->identityProviderClass), - Redirect::class => $this->setUpRedirect(), - 'request' => $this->setUpMockService(Request::class), - ]; - } - - /** - * @param Request $request - * @param RouteMatch $routeMatch - * @return MvcEvent - */ - protected function setUpMvcEvent(Request $request, RouteMatch $routeMatch): MvcEvent - { - $event = new MvcEvent(); - $event->setRequest($request); - $event->setRouteMatch($routeMatch); - $router = $this->setUpMockService(TreeRouteStack::class); - $event->setRouter($router); - return $event; - } - - /** - * @param ServiceLocatorInterface $serviceLocator - * @return PluginManager - */ - protected function setUpPluginManager(ServiceLocatorInterface $serviceLocator): PluginManager + protected function setup(): void { - $pluginManager = new PluginManager($serviceLocator); - return $pluginManager; + $this->identityProviderMock = m::mock(IdentityProviderInterface::class); + $this->redirectHelperMock = m::mock(Redirect::class); } /** * @param ServiceLocatorInterface $serviceLocator * @param Request $request * @param RouteMatch|null $routeMatch - * @return SessionTimeoutController */ - protected function setUpSut(ServiceLocatorInterface $serviceLocator, Request $request): SessionTimeoutController + protected function setUpSut() { - $routeMatch = new RouteMatch([]); - $factory = new SessionTimeoutControllerFactory(); - $instance = $factory->__invoke($serviceLocator, SessionTimeoutController::class); - $instance->setEvent($this->setUpMvcEvent($request, $routeMatch)); - $instance->setPluginManager($this->setUpPluginManager($serviceLocator)); - - // Dispatch a request so that the request gets set on the controller. - $instance->dispatch($request); - - return $instance->getDelegate(); + $this->sut = new SessionTimeoutController( + $this->identityProviderMock, + $this->redirectHelperMock + ); } /** @@ -266,67 +170,17 @@ protected function setUpRequest(?string $url = null, array $input = null) return $request; } - /** - * @param string $identityProvider - * @return m\MockInterface - */ - protected function setUpIdentity(string $identityProvider): m\MockInterface - { - $identity = $this->setUpMockService(User::class); - $identity->shouldReceive('isAnonymous') - ->andReturnFalse() - ->byDefault(); - - $currentUser = $this->getMockServiceWithName($identityProvider, IdentityProviderInterface::class); - $currentUser->shouldReceive('getIdentity') - ->withNoArgs() - ->andReturn($identity) - ->byDefault(); - $currentUser->expects('clearSession') - ->never() - ->byDefault(); - - return $currentUser; - } - - protected function getMockServiceWithName(string $class, string $serviceName): MockInterface - { - if (!$this->serviceManager->has($serviceName)) { - $this->serviceManager->setService( - $serviceName, - $this->setUpMockService($class) - ); - } - - return $this->serviceManager->get($serviceName); - } - - protected function setUpIdentityWithClearSession(string $identityProvider): void + protected function setUpIdentityWithClearSession(): void { - $identity = $this->setUpMockService(User::class); + $identity = m::mock(User::class); $identity->expects('isAnonymous') ->withNoArgs() ->andReturnFalse(); - $currentUser = $this->getMockServiceWithName($identityProvider, IdentityProviderInterface::class); - $currentUser->expects('getIdentity') + $this->identityProviderMock->expects('getIdentity') ->withNoArgs() ->andReturn($identity); - $currentUser->expects('clearSession') + $this->identityProviderMock->expects('clearSession') ->withNoArgs(); } - - /** - * @return m\MockInterface - */ - protected function setUpRedirect(): m\MockInterface - { - $redirect = $this->setUpMockService(Redirect::class); - $redirect->shouldReceive('refresh') - ->withNoArgs() - ->andReturn(new Response()) - ->byDefault(); - - return $redirect; - } }