1

I am trying to test database records retrieving. My test looks like:

use yii\db\Exception;

class UserTest extends Unit
{
    protected $tester;
    private $_user;

    public function _before()
    {
        $this->_user = new User();
    }

    public function testRetrievingFALSE()
    {
       $this->expectException(Exception::class, function(){
          $this->_user->retrieveRecords();
       });
    }
}

I saw the expectException() method in the documentation. My model method looks like this:

public function retrieveRecords()
{
    $out = ArrayHelper::map(User::find()->all(), 'id', 'username');
    if($out)
        return $out;
    else
        throw new Exception('No records', 'Still no records in db');
}

What am I doing wrong in this scenario?

In terminal:
Frontend\tests.unit Tests (1) ------------------------------------------------------------------------------------------
x UserTest: Retrieving false (0.02s)
------------------------------------------------------------------------------------------------------------------------


Time: 532 ms, Memory: 10.00MB

There was 1 failure:

---------
1) UserTest: Retrieving false
 Test  tests\unit\models\UserTest.php:testRetrievingFALSE
Failed asserting that exception of type "yii\db\Exception" is thrown.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
2
  • It looks like you dot not mock your model and make a real query to database. Are you sure that you do not have any record on database? Commented Sep 27, 2018 at 9:05
  • Yup. Totally clear. I am still learning so I made database just for test. 1 table with no records. Will edit the error. Commented Sep 27, 2018 at 10:03

1 Answer 1

5

You're not using the same method which you're referring to. You should use it on actor instance, not on unit test class itself. So either:

$this->tester->expectException(Exception::class, function(){
    $this->_user->retrieveRecords();
});

Or in acceptance tests:

public function testRetrievingFALSE(AcceptanceTester $I) {
    $I->expectException(Exception::class, function(){
        $this->_user->retrieveRecords();
    });
}

If you call it on $this in test class, method from PHPUnit will be used, which works differently:

public function testRetrievingFALSE() {
    $this->expectException(Exception::class);
    $this->_user->retrieveRecords();
}

See more examples in PHPUnit documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.