Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

php - Is this unit test correctly?

I have this method (sending a message from one user to another):

/**
     * Create message after sending by  user.
     *
     * @param       $from
     * @param       $to
     * @param       $message
     *
     * @return bool
     * @throws Exception
     */
    public function createMessage($from, $to, $message)
    {
        $userFrom = User::findOrFail($from);
        $userTo = User::findOrFail($to);

        if(strlen($message) < 1 || strlen($message) > 255)
            throw new InvalidArgumentException('Invalid size of message in createMessage', 422);

        if(!$userFrom->id || !$userFrom->login || !$userTo->id || !$userTo->login) {
            throw new Exception("The user has not <id> or <login> columns or they are empty.", 500);
        }

        return DB::table('messages')->insert(
            [
                'from'       => $userFrom->id,
                'to'         => $userTo->id,
                'from_login' => $userFrom->login,
                'to_login'   => $userTo->login,
                'message'    => $message,
            ]
        );
    }

Have I handled all kinds of errors correctly? For this method, I wrote the following tests. Here's an example, and the rest are just titles.

/** @test */
    public function null_message_send()
    {
        $this->expectException(InvalidArgumentException::class);
        $user1 = User::factory()->create();
        $user2 = User::factory()->create();
        $writeMessageRepository = resolve(WriteMessageRepository::class);
        $result = $writeMessageRepository->createMessage($user1->id, $user2->id, '');

        $this->assertFalse($result);
        $this->assertDatabaseMissing('messages', ['from' => $user1, 'to' => $user2->id, 'message' => '']);
    }

and...

public function success_send_message()
public function null_user_from_test()
public function null_user_to_test()
public function very_large_message_send()
public function two_users_are_null()

I'm just learning how to write tests, so please write what I'm doing wrong. Did I do everything right? Are there any unnecessary tests that make no sense? Or unnecessary checks? Or, on the contrary, is something missing? Should I also write same tests for all controllers, services, repositories methods? UPD: is it a good structure to create a folder for each class and describe one method from all sides in each test?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...