spacedog4's avatar

Do something when Unit Test fails

In my test I create a model so I can test my command, but if the test fails, I want to remove my model but it never reachs File::delete(app_path() . '/Test.php'); How can I make some method that reachs when the assert fails?

public function test_if_it_generate_view_files()
    {
        $model_name = 'Test';

        Artisan::call('make:model', [
            'name' => 'Test'
        ]);

        Artisan::call('make:view', [
            'name' => $model_name
        ]);

        $base_path = resource_path() . '/views/admin/' . strtolower($model_name);
        $index_path = $base_path . '/index.blade.php';

        $this->assertFileExists($index_path);
        $this->assertFileEquals(__DIR__ . '/acceptance/stubs/views/admin/test/index.stub', $index_path);

        File::deleteDirectory($base_path);
        File::delete(app_path() . '/Test.php');
    }
0 likes
2 replies
click's avatar
click
Best Answer
Level 35

Normally you do things like this in setUp() and tearDown() methods within your test class. These methods are always called just before and just after your test method is executed.

Another approach would be to wrap your assertions in a try catch.... didn't test it but I think it should work.

try {
        $this->assertFileExists($index_path);
        $this->assertFileEquals(__DIR__ . '/acceptance/stubs/views/admin/test/index.stub', $index_path);
} catch (\Exception $e) {
    File::deleteDirectory($base_path);
    File::delete(app_path() . '/Test.php');
    throw $e;
}
1 like

Please or to participate in this conversation.