BernardoBF4's avatar

Test not covering all my code

When writing tests Uncle Bob says we should only write the minimum of code to make the test pass. In my case bellow where I have the test, controller and service, it is not what happened, but I don't know how to make it different. As you can see, my test tests if a logged user can create a group: it's simply the action of storing a group (name, status and relation to a modules table) on the database, as my service makes clear, but in my service I am doing more than just creating the group, I am also checking if there's no errors to the queries and wrapping everything on a try-catch block. That seems more than just one thing, it seems like two or even three. The point is: by adding more behaviour to a function than what the test tests makes the test not cover everything it says it does, so what would be a solution for this?

  /** @test */
  public function a_logged_user_can_create_a_group()
  {
    $this->withoutExceptionHandling()->signIn();

    $group_data = [
      'name' => $this->faker->word(),
      'status' => $this->faker->boolean(),
    ];
    $modules = ['modules' => Modules::factory(1)->create()->pluck('id')];

    $response = $this->post(route('cms.groups.store'), array_merge($group_data, $modules));

    $response->assertSessionHas('message', trans('cms.groups.success_create'));
  }
  public function store(GroupRequest $request)
  {
    $result = $this->group_service->createGroupWith($request->all());

    return redirect()->back()->with('message', $result['msg']);
  }
public function createGroupWith($data)
  {
    try {
      DB::beginTransaction();

      $modules_id = array_pop($data);

      $group = Group::create($data);
      $group->modules()->attach($modules_id);

      DB::commit();
      return ['msg' => trans('cms.groups.success_create')];
    } catch (\Throwable $error) {
      DB::rollBack();
      return ['msg' => $error->getMessage()];
    }
  }
0 likes
2 replies
jlrdw's avatar

There are several videos here on laracasts covering testing, many are free. Just my opinion, but just test like @jeffreyway does.

Just FYI, I have seen many questions where test fail, but code actually works in real World.

I generally like some test to help refactor code, not to see if for example a login works. But just my opinion.

2 likes
Sinnbeck's avatar

You are allowed to test the same code in multiple ways to take different paths. These together should get you towards 100%.

Be aware that 100% isn't the goal. The goal is to make sure that you are confident that you can make changes without breaking anything

2 likes

Please or to participate in this conversation.