Loading
Current section: Functions 5 exercises
Problem

Mock implementation

Loading exercise

Transcript

00:00 When you spy on a function, you're asking your testing framework to record all the calls that happen to that function. And that's extremely powerful, but sometimes it's not enough. Sometimes you want to affect the behavior of that spied function. Here, let me show you.

00:15 In this OrderController class, we have a createOrder method that accepts a cart and should create an order object based on those cart items. Before it does, though, it makes sure that all the cart items are in stock. And if some are not, it throws an error featuring the items that are not

00:32 in stock. But if everything is good to go, it creates the order object, returning the cart as is. So to know which items are in stock or not, this class has a method called IsItemInStock, and it checks the item availability in this StocksChasen object. It makes sure that the

00:49 item by the given ID exists and also has sufficient quantity for the order. But what is this StockChasen? Well, in this exercise, it's just a static chasen file, but you can think about it as any source of data, like a database, for example.

01:04 In this exercise, your task will be to test this createOrder method and to test both of its behaviors, the successful behavior when the order is created, but also an error behavior when some of the cart items are not available. And to tweak these two behaviors and switch between them in

01:21 test, you would have to spy on this IsItemInStock method, but also mock its implementation. This is going to be a fun exercise, and see you in the solution very soon.