Hướng dẫn phpunit before all
Currently we run code to setup the database in setUpBeforeClass. However this runs before every test class is tested. Is it possible to have code run once before any tests are run, and maybe run some code when all tests are complete too? Show asked Nov 10, 2011 at 20:10
1 This is precisely what the bootstrap file is designed to handle. By default PHPUnit will execute the code in This file is executed exactly once before trying to locate the tests to be run. It allows you to set up an include path, autoloader, constants, etc. before instantiating or running any tests. answered Nov 11, 2011 at 3:36
David HarknessDavid Harkness 35.2k10 gold badges111 silver badges129 bronze badges 1 I agree with Kris's comment that you want to avoid this sort of behavior, but if you need to, perhaps you could do something like this:
Then make sure your tests extend My_PHPUnit_Framework_TestCase instead of PHPUnit_Framework_TestCase. answered Nov 10, 2011 at 20:46
Adam V.Adam V. 1,7251 gold badge16 silver badges18 bronze badges 3 Why would you want to do that? Unit tests should be independent of each other, and thus should all preconditions also be restored to the same state before every test is run. If you feel the need to have an initialization method that runs once for the entire suite, your tests are probably not set up right. answered Nov 10, 2011 at 20:21
KrisKris 2,05817 silver badges19 bronze badges 2 Đã đăng vào thg 11 30, 2021 4:05 SA 4 phút đọc 1. Giới thiệu UnitTest
2. Cấu trúc thư mục test trong Laravel
3. Tạo mới và chạy UnitTest
Câu lệnh trên sẽ tạo một file test có đường dẫn tests/Unit/Models/UserTest.php
4. Assertions
5. Một số ví dụ về UnitTest
Ví dụ, ta có Model Post như dưới đây:
Class test của chúng ta như sau, ở đây ta thực hiện test relationship giữa Post và User:
Ví dụ, ta có một PostRepository với method create như dưới đây:
Class test của chúng ta như sau:
6. Reset database sau khi test
7. Tổng kếtHi vọng bài viết này sẽ cung cấp cho mọi người cái nhìn tổng quan về UnitTest trong Laravel và có thể áp dụng được trong công việc của mình. Cảm ơn mọi người đã đọc bài. Tham khảo:
All rights reserved |