From the course: PHP: Design Patterns

Introducing mock objects - PHP Tutorial

From the course: PHP: Design Patterns

Start my 1-month free trial

Introducing mock objects

- Now Mocks are an interesting thing. At first glance they really don't make a ton of sense. Why would you want an object that just copies another but without most of the business logic? How and when does this make sense? But before we dive into the why let's settle a bit of a dispute. If you read other sources on Mocks you may also hear the concepts of Fakes and Stubs. While there are some subtle distinctions in the implementation details between the various patterns, quite a bit of the semantics are tied to the implementation itself. If you read about any of these things in the wild, know that they're essentially the same but implemented slightly differently. Don't get confused there. Anyway, back to our story. So now let's talk about the problem we're solving. Quite often in our code there are side effects. For example: when you create a new user you probably send an e-mail to confirm their account. Then you have to wait on the user to click the link. When we're building e-commerce or membership systems we might charge a credit card. In development you're probably working with test credentials or sample card numbers. So this might be acceptable. As your system gets more complex and moves into production this becomes less acceptable and harder to prove that things are working as expected. So we need a better solution. Enter Mock Objects. Why is this useful? Why would we want to use objects that don't actually do any work? Well that's kind of the point: when we have an object that we can completely control we can do something interesting; and useful things with it. Namely, for Unit Testing. When we want to do Unit Testing of our system or its components we need to be able to fake or mock certain types of behavior. For example, if you're testing your e-mail templating system you don't actually want to send e-mails. But you want the system to act like it did. This is where we use a mock. But there's a downside to using mocks. Since they end up imitating external behavior, it's common for them to also imitate internal behavior. So you get this class that looks and acts like the original class from the outside. But also implements some of the internal logic. This is less than ideal and you should work to limit that. Further, as long as you're implementing the internal behavior you'll have this desire to test it. So you end up with logic that is not only duplicated, but tested twice. Overall this leads to the final drawback: you now have all these tests that are passing, but still designed specifically for the mock. You could easily come to the conclusion that your system is better tested than it is. But enough with the definition and downsides. Let's talk about a real world example.

Contents