0

How could I test method Bar::foo?

class Foo {
    protected function foo() {
        // Do something
    }
}

class Bar extends Foo {
    protected function foo() {
        parent::foo();
        // Do something else
    }
}

I need to mock Foo::foo and not to have

Fatal error: Access level to Bar::foo() must be public (as in class Foo)...

??

3
  • Are you sure that Foo::foo is protected? The error message is telling you otherwise. Foo::foo is public there, which means Bar is breaking the inherited contract. A child class can turn a protected method into a public one (increasing visibility), but it can't restrict the visibility (ie public to protected is not allowed). Either way: use a reflection class to make the method public and you're set Jun 2, 2015 at 10:56
  • It becomes public when I'm trying to mock it. Jun 2, 2015 at 11:05
  • What class/object are you mocking, where and how? Bar or Foo, and how are you changing the visibility to public? show the code Jun 2, 2015 at 11:24

1 Answer 1

0

You don't need to mock Foo::foo to test your method. The fact that it calls the parent's foo method is an implementation detail. You don't need to make sure that a Bar object calls any of Foo's methods. The only thing that you would assert is that Bar is an instance of Foo.

From your example, you don't even need to explicitly test Bar::foo either because it is a protected method. If Bar::foo is complicated enough that you think that you need to write a test for it. Consider refactoring it to its own class and using the Strategy pattern for Bar.

You don't want your tests checking whether or not internal methods are called. This makes refactoring your classes much more difficult. Your test should pass if you were to copy all the lines from Foo::foo into Bar::foo. It isn't good coding practice. But tests don't ensure good code. They ensure that code works correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.