0

I am writing my first controller test. Internally the controller must call (or extend) a file that tries to connect to the database. However, I don't want it to actually connect to a database, since that's not exactly what I'm testing right now (...or should I?). Anyway, how can I mock/stub (not sure what the correct terminology is) a call to the database? Or, how can I at least intercept any calls so I know where they are all happening?

edorian
  • 38,542
  • 15
  • 125
  • 143
Andrew
  • 227,796
  • 193
  • 515
  • 708

1 Answers1

1

General answer: Yes "mocking" is the right term here. You want to create a 'fake' object that takes known inputs and produces known outputs.

First of all: I don't have experience with testing Zend Framework Controllers. Judging from the SO questions that seems to be rather complicated. So without some sample code i can't produce a working/sort-of-working example.

However, I don't want it to actually connect to a database, since that's not exactly what I'm testing right now (...or should I?).

First of: I'm not sure if you want to actually connect to the database. The 'pure' form of unit testing tells you to work against a fake database (sqlite, in memomry) while I currently like to make sure my queries work against a real db instance so i test my databases access objects again the real db. Which brings me to the next point.

Your controller shouldn't talk to the database. Even (all/many) models talking directly to database is not what many people consider proper MVC but putting SQL in controllers is the php equivalent of putting html in your application-logic PHP code back in the php 4 days.

As a very general answer:

Look in the code where you get your $objectToMockOutInQuestion. When it comes from a method for constructor parameter you've won and you can just pass it in. When your code pulls it from a container see if you can but it in that container beforehand. If it's a plain old new operator you might want to change your code.

Hope that helps even so it's only text

edorian
  • 38,542
  • 15
  • 125
  • 143