1

I'm new with unit testing and I'm trying to write a test for this plugin...

    /**
     * @param AccountManagement $subject
     * @param CustomerInterface $customer
     * @param null $password
     * @param string $redirectUrl
     * @return array
     */
    public function beforeCreateAccount(
        AccountManagement $subject,
        CustomerInterface $customer,
        $password = null,
        $redirectUrl = ''
    ) {

        $customer->setFirstname(str_replace(' ', '', $customer->getFirstname()));

        return [$customer, $password, $redirectUrl];
    }

Ant this is my approach to writing the test...

    public function setUp(): void
    {
        $this->createMock(AccountManagement::class);

        $this->accountManagementPluginClass = new AccountManagementPlugin();
    }

    public function testBeforeCreateAccount()
    {
        $customerMok = $this->createMock(Customer::class);
        $customerMok->expects()->method('getFirstName')->willReturn('Diego Maradona');
        // I tried this instead too
        // $customerMok->setFirstName('Diego Maradona')

        $arr = $this->accountManagementPluginClass->beforeCreateAccount(
            $this->createMock(AccountManagement::class),
            $customerMok
        );

        $this->assertEquals('DiegoMaradona', $arr[0]->getFirstName());
    }

I know that the problem is that the mock objects have no logic. The only return is the mock value. So which is the right way to test a method who:

  • receive an object as a parameter (Ex: $customer)
  • modify that object (Ex: $customer->setFirstName())
  • return the object modified (Ex: $customer->getFirstName())
1
  • need solution for the same Commented Jul 6, 2022 at 9:28

1 Answer 1

1

The reason why it's not working is because your plugin can't modify a mocked object. The correct way is to use the test ObjectManager for the customer data model object. In fact, most data models should be instantiated rather than mocked. Here's your code, modified but untested:

public function setUp(): void
{
    $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
    
    $this->accountManagementPluginClass = new AccountManagementPlugin();
}

public function testBeforeCreateAccount()
{
    $customer = $this->objectManager->getObject(Customer::class, []);
    $customer->setFirstname('Diego Maradona');
    
    $arr = $this->accountManagementPluginClass->beforeCreateAccount(
        $this->createMock(AccountManagement::class),
        $customer
        );
    
    $this->assertEquals('DiegoMaradona', $arr[0]->getFirstName());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.