B
B
BonBon Slick2018-05-14 15:19:56
symfony
BonBon Slick, 2018-05-14 15:19:56

Test for EncoderFactoryInterface?

test

/** @var EncoderFactoryInterface|MockObject $encoderFactory */
        $encoderFactory = $this->getMockBuilder(EncoderFactoryInterface::class)
            ->setMethods(['getEncoder'])
            ->disableOriginalConstructor()
            ->getMock();
        $encoderFactory->expects($this->once())
            ->method('getEncoder');
        $this->assertInstanceOf(EncoderFactoryInterface::class, $encoderFactory);

// trigger encoder getEncoder method

public function __construct(
        EncoderFactoryInterface $encoderFactory,
....
 dump($this->encoderFactory->getEncoder($newUser)); // NULL
        $encodedPass = $this->encoderFactory->getEncoder($newUser)->encodePassword(
            $newUser->plainPassword()->plainPassword(),
            $newUser->salt()->salt()
        );

Will return null and the test will fail. Why? There is a real entity both without a test and in a test, but without a mock it works as it should.
I did the same with UserPasswordEncoderInterface, tried to manually encode, anyway when trying
$this->userPasswordEncoder->encodePassword($newUser, $data['password'])
will return null.
I looked at the tests from vendors for these interfaces, I seem to be doing everything the same
class EncoderFactoryTest extends TestCase
{
    public function testGetEncoderWithMessageDigestEncoder()
    {
        ...
        $encoder = $factory
->getEncoder($this
->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface') // тут у меня юзер с этим интерфейсом 
->getMock());
        $expectedEncoder = new MessageDigestPasswordEncoder('sha512', true, 5);

        $this->assertEquals($expectedEncoder->encodePassword('foo', 'moo'), $encoder->encodePassword('foo', 'moo'));
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
voronkovich, 2018-05-14
@BonBonSlick

You need to set the behavior of the getEncoder method with willReturn :

$encoderFactory = $this->createMock(EncoderFactoryInterface::class);

$encoderFactory
    ->method('getEncoder')
    ->willReturn($encoder);

I advise you to read the documentation: Test Doubles .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question