Tuesday, March 21, 2017

Database Transactions on Unit Testing Lumen / Laravel

I am quite new to unit testing, and currently writing my first integration tests. I have a JSON API where a product should only be inserted in the database when the key not exists already. When i testing it manually while cleaning up the database before every thing works. But the test always fails:

This is my test code:

class ProductsTest extends TestCase
{   
    use DatabaseTransactions;

    public function test_product_creation_fails_when_same_key()
    {
    $product = new Product(['Product 1', 'key']);
    $product->save();

    $this->json('POST', '/products', ['name' => 'Product 2', 'key' => 'key'])
        ->seeJSON(['error' => '500'])
        ->assertResponseStatus(400);
    }
    ...

PHPUnit gives the following errors:

There was 1 error:

1) ProductsTest::test_product_creation_fails_when_same_key
PHPUnit_Framework_ExpectationFailedException: Unable to find JSON fragment ["error":"500"] within [{"created_at":"2017-03-21 13:45:08","id":9,"key":"backsys","name":"BackSys 2","updated_at":"2017-03-21 13:45:08"}].
Failed asserting that false is true.

Which seems that the creation of the second product does not fails. Which it should...

Im sensing that there is an error of unterstanding in the usage of my transactions maybe? Or the transactions are rolled back already when i try to call ´$this->json´ ?



via Reflic

Advertisement