A service by the name "api-identity" or alias already exists

When using Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase::dispatch-method twice within the same method (no setUp() or tearDown() inbetween) I get the following error message when running the tests:

Zend\ServiceManager\Exception\InvalidServiceNameException: Zend\ServiceManager\ServiceManager::setService: A service by the name "api-identity" or alias already exists and cannot be overridden, please use an alternate name.


using the following code in 
ZF\MvcAuth\Module
fixes the problem:


    public function onAuthenticationPost(MvcAuthEvent $e)
    {
        if (!$this->services->has('api-identity')) {
            $this->services->setService('api-identity', $e->getIdentity());
        }
    }