How to mock the class without passing parameter

Asked

Viewed 91 times

1

Using Phpunit I can mock a class and pass by parameter and test a method is case of selectById. But I can’t mock Acesso and test pessoaLogadaIgualPessoaAtividade.

How to take the test of Pessoa->pessoaLogadaIgualPessoaAtividade?

class Pessoa
{
    private $dao = null;
    public function setDao($dao)
    {
        $this->dao = $dao;
    }    
    public function selectById( $id )
    {
        $result = $this->dao->selectById( $id );
        return $result;
    }
    public function pessoaLogadaIgualPessoaAtividade( $idPessoaAtividade ){
        $result = false;
        $controllerAcesso = new Acesso();
        $idPessoaLogada = $controllerAcesso->getUserId();   
        if( $idPessoaLogada == $idPessoaAtividade) {
            $result = true;
        }
        return $result;
    }

For the test I’m trying to do:

    public function testPessoaLogadaIgualPessoaAtividade_true()
    {
        $mock = $this->createMock(Acesso::class);
        $mock->method('getUserId')->willReturn(1);

        $pessoa = new Pessoa();

        $expected = true;
        $result = $pessoa->pessoaLogadaIgualPessoaAtividade(1);
        $this->assertEquals($expected, $result);
    }

This question helped me to take the test of selectById.

  • if creating the object of type Acesso within the class will be impossible to mock, need to use dependency injection to be able to mock and test, basically need to receive by parameter the type Acesso, thus: public function pessoaLogadaIgualPessoaAtividade( $idPessoaAtividade, Acesso $controllerAcesso ){. I can’t write a detailed answer now, but if you follow this other answer from the OS I think you’ll understand: https://stackoverflow.com/a/18564335/4730201 If you still have doubt, leave a comment that as soon as you can put a more explanatory example

1 answer

0


There are some ways to do this.

Since Phpunit uses test classes to create them, so you can use the conventional object orientation paradigm by creating a constructor for her class and make the injections of dependencies necessary for her and then only access them by attributes, not forgetting that private objects are not seen outside the class itself.

For example:

private $id

If Voce has a private id and you want that object to propagate to the PHP methods Unit Voce has to do the proper encapsulation of it using:

public function setId($id = null)
{
    $this->id = $id;
}

public function getId(): int // espera-se que o seu ID seja um integer ,caso contrário so mudar o tipo de retorno.
{
    return $this->id;
}

This article here is very detailed explaining.

I hope to have helped and mainly clearly stepped what you would like to do, otherwise please give me more details that will be a pleasure to help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.