3

I am kind of new to testing and I would like to understand how testing is implemented in a real world scenario. For instance, There is this code which implements an internal framework, and employs method chaining. At first glance I assumed mocking would be the best way to go, but most examples go this way:

public function someFunction(A $a)
{
    return $a * b;
}

However, the code I am testing goes this way:

public function deleteUser($user_id)
{
    $user_id = (int)$user_id;
    $flag = Framework::getInstance()->request->get('delete') || false;

    if (!$this->exists($user_id)) {
        throw new UserException(UserException::NOT_EXIST);
    }

    return $this->delete([
        'id' => $user_id
    ]);
}

How would you test it?

I have looked at "Testing objects with dependencies in PHPUnit", but modifying the actual code is not an option.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Ego_I
  • 350
  • 3
  • 14

1 Answers1

3

Short answer: you can't unit test that code. The code is too coupled to the Framework class due to the static method call, so you can't test the deleteUser() method in isolation. This article about testing code that uses Singletons describes the situation pretty well.

The long answer is that you can't unit test that code, but you can still create tests that are useful, like integration tests or functional tests. You can use this question as reference, but basically, in an integration test you test several parts of your code working together at the same time. In this kind of tests, you could test the expected behavior for this method, which is that a user is being deleted, without worrying about the dependencies of your class. You want to test both classes (class under test and Framework class) working together, so you don't need to mock anything.

Having said that, why can't you just change the code? I'd strongly suggest to inject the dependencies to your code (as said in the first article) instead of using a singleton.

Community
  • 1
  • 1
Jose Armesto
  • 12,794
  • 8
  • 51
  • 56
  • Well, its the company framework, so modifying it is not really an option. Thanks though, after spending a few days racking my brain I had come to the same conclusion you had.... Testing would be near impossible – Ego_I Mar 22 '13 at 04:54
  • You could try other kind of testing like integration tests or functional tests. But yes: unit testing is not possible. If the answer was helpful, please don't forget to accept it! :) – Jose Armesto Mar 22 '13 at 08:06