#How many test case is for best practice?

9 messages · Page 1 of 1 (latest)

brazen zodiac
#

Hey, so im new with unit testing. how many test case you guys usually made for simple crud? i made 30+ test cases for a simple crud and it's so tiring for me, is there a faster way to make test cases? here is some of my code

i check these for index,create,store,edit,update and delete

  • page rendered successfully
  • authorization
  • check user permission
  • check request validation
  • check data exist or dont
  • check action success
beforeEach(function () {
    $this->user = User::where('email', '[email protected]')->first();
    $this->user2 = User::factory()->create();
    $this->post = [
        'name' => 'Super Admin testing',
    ];
    $this->post_update = [
        'name' => 'Super Admin testing Updated',
    ];
    $this->notfound_id = 999;
});
// CREATE
test('render create page unauthorize', function () {
    $this->get(route('role.create'))
        ->assertStatus(302)
        ->assertRedirect('/login');
});

// STORE
test('create role unauthorize', function () {
    $this->post(route('role.store'), $this->post)
        ->assertStatus(302)
        ->assertRedirect('/login');
});

test('create role no permission', function () {
    $response = $this->actingAs($this->user2)->post(route('role.store'));
    $response->assertStatus(403);
});

test('create role success', function () {
    $this->actingAs($this->user)
        ->post(route('role.store'), $this->post)
        ->assertStatus(201)
        ->assertJson([
            'data' => [
                'name' => $this->post['name'],
            ],
        ]);
});

test('create role duplicate name', function () {
    Role::create($this->post);

    $this->actingAs($this->user)
        ->post(route('role.store'), $this->post)
        ->assertStatus(400)
        ->assertJson([
            'message' => 'Form Validation Error',
            'errors' => [
                'name' => ['Role name has been used'],
            ],
        ]);
});

umbral topaz
#

I think if you want full coverage there is no other way, this is why software takes so long — if you do it properly.

brazen zodiac
umbral topaz
#

But it gets stuck with feature tests, from what I can gather, small unit tests seem okay-ish

brazen zodiac
deft linden
#

You can of course re-use the same tests across swathes of your code-base for CRUD type things.

For example, if you have a field that should be "unique", you can just call a method that runs the test that it is validating correctly "when it is unique", "when it is a duplicate"

#

etc

#

You could take a risk based approach that Laravel Core code will work (and is tested in the core test suites) and not bother testing things like duplicate name testing etc, and worry more about your application logic tests
This is more dependent on whether you have teams of people working on your project, or just one, and is more assurance that your validation rules are present