Testing modules using the Active Record framework

I am using an ORM-based framework on the Active Recording Image . Every table that I have in my database is tied to a model in my code.

I want to use the unit test for these models, so I started by extracting all the calls to save()and update()from the models, so that changes are made only on the objects, and they are only saved after necessary.

I do not know how I can apply this strategy in this case. I have a model Chatin which a Useris a part, and Usercan add ChatNoteto Chat.

Here's the current implementation:

// User.php
public function addChatNote($chatNoteContent, Chat $chat)
{
    $chatNote = new ChatNote();
    $chatNote->content = $chatNoteContent;
    $chatNote->save();

    $chat->note()->associate($chatNote);
    $chat->save();
}

, , , save() .

ChatNote , ? Chat , User - , ChatNote Chat? save()?

+4
3

@user3807702 , AbstractFactory Factory method Unit Testing . .

public function addChatNote($chatNoteContent, Chat $chat)
{
    $chatNote = $this->chatNoteFactory->newInstance();
    $chatNote->content = $chatNoteContent;
    $chatNote->save();

    $chat->note()->associate($chatNote);
    $chat->save();
}

ChatNote mock, .

$chatNote = $this->getMockBuilder(ChatNote::class)
                ->disableConstructor()
                ->setMethods(['save'])
                ->getMock();

$chatNoteFactoryMock = $this
    ->getMockBuilder(chatNoteFactoryMock::class)
    ->getMock();

$chatNoteFactoryMock
   ->method('newInstance')
   ->willReturn($chatNote);

//Pass the chat note factory mock to the User

Chat - addChatNote. , DB.

- , save User " " . User , Chat ChatNote DB. saves : -, AOP ..

0

, ChatNoteFactory, ChatNote, .

+2

, xunit , , , . , - . , , . , .

( )

, , Laravel. .

In normal Antoher practice, a separate in-memory database is used for testing. You can even create a diagram from scratch (all migrations) before each test. Just add this to your phpunit.xml:

<php>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
</php>
+2
source

Source: https://habr.com/ru/post/1675964/


All Articles