在另一个类中使用语句

I am going through a Laracast tutorial which suggest me to have the statement use DatabaseTransactions; inside my test class definition, to allow the data changes in my test case will persists only for that case. I have a test class,

    Class MyClassTest extends TestCase
    {

    // This use statement is responsible for 
    //all the data operations to persists only with in that test case
    use DatabaseTransactions;
     /**
     * @test
     */  
     public function my_test_function()
    {
     // My test case code. Which inserts/updates 
     //data and assert statement.
    }
    }

The use DatabaseTransactions works in a way that the data changes in the method persists only with in that. How that works exactly?

As went further, DatabaseTransactions is trait, which contains the method beginDatabaseTransaction with @before annotation.

  • Having an use DatabaseTransactions within the test class lets the class have that method.
  • Since the method beginDatabaseTransaction contains a @before annotation, it will be executed before every test case.
  • The below is the method definition which begins a transaction and rolls back existing transaction before the test case finishes(it is still unclear why @before should be called before the test case finishes).

    @before

    public function beginDatabaseTransaction() {

    $this->app->make('db')->beginTransaction();
    
    $this->beforeApplicationDestroyed(function () {
        $this->app->make('db')->rollBack();
    });
    

    }