B
B
badicean2016-05-24 15:08:05
PHP
badicean, 2016-05-24 15:08:05

Am I writing mocks correctly?

I'm testing a certain event, everything works fine. Can you please tell me if I am using phpunit features correctly?

public function test_mp_bid_update()
    {
        $advert_id = rand(1,9);

        // mock form
        $user_data = $this->getMock('AdvertForm');
        $user_data->hash = $this->hash;

        // mock advert
        $advert = new Advert();
        $advert->id = $advert_id;

        $publisher = $this->getMockBuilder('AdvertPublisher')
                            ->setConstructorArgs([$user_data])
                            ->getMock();
        $publisher->advert = $advert;

        $event_mock = $this->getMock('CEvent');
        $event_mock->sender = $publisher;

        $event_handler = new UpdateMpBidEvent();
        $event_handler->call($event_mock);

        $updated_mp_bid = MpBid::model()->findByAttributes(['hash'=>$this->hash]);
        $this->assertEquals($advert_id, $updated_mp_bid->advert_id);


    }

The event itself
<?php
class UpdateMpBidEvent
{
    public function call(CEvent $event)
    {
        $advert_id = $event->sender->advert->id;
        $hash = $event->sender->user_data->hash;
        $mp_bid_updated = MpBid::model()
                                    ->findByAttributes(['hash'=>$hash])
                                    ->updateAll(['advert_id'=>$advert_id]);
        return $mp_bid_updated;
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
index0h, 2016-05-25
@badicean

krofIzGlaz.jpg
Have you ever wondered why it is possible to replace methods in mocks, but not properties?
The main point of a mock is that you can define and control its behavior.
1. Read about PSR, don't breed kaku.
2. Moki makes sense to do without a constructor AND prescribe stubs for called methods.
3. Methods that should not be called are also replaced by stubs, but in expects, ban never.
4. Try not to use static as much as possible. It can only be tested indirectly.
5. Try to keep SOLID. In your example, this may be an unfortunate name, of course, but an event, as a rule, is a kind of data collection, you should not burden it with logic.
6. Working with a database in ActiveRecord can be convenient, but for tests - this is shit, from the point of view of security and extension - alas, too. Specifically, in your case, create a separate method that will update your identifier, write a test for it that will work with the database. For an event, you should only check that the method was called with the correct data.

D
Denis Ineshin, 2015-08-16
@IonDen

In no case! To program, you need a full-fledged computer. So look towards cheap laptops.

E
Evgeny Elchev, 2015-08-16
@rsi

Are you seriously? It's hell. You need a normal PC, the more powerful the better, preferably with two monitors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question