BernardoBF4's avatar

Unit and Feature test for Services

I have a feature test where I post some data to an API route and validate the result. This API has its controller which calls a service method. The test is presented bellow, with the controller and service following. My question is: if I have a feature test, should I have a unit test to test the behaviour of the service method?

This is because in the test bellow, I am testing the message that will be showed to the user but it feels a little weird to not have a database test, to check if the data I posted to the API is really stored in the right table, so I imagine it should be a unit test. Is this valid or is it redundant?

  /** @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
0 replies

Please or to participate in this conversation.