Lab04 inject repo api
Goal¶
In this lab, you'll have the API controller use the newly created MealOrderRepository
to store new MealOrder
s.
Annotation Reference
This reference of annotations is good to keep handy: http://engineering.pivotal.io/post/must-know-spring-boot-annotations-controllers/
A. Clean Up MealOrder¶
Now that we have MealBuilder
, we can get rid of the overloaded constructors in MealOrder
.
They were useful once, but they're now "cruft" and we want to delete unused code.
- Run all tests!
- Delete all of the constructors from
MealOrder
- Run all tests.
- If you had any usages of these non-default constructors, replace them with using the
MealBuilder
- Are tests still passing?
B. Store Created MealOrders in Repository¶
In the MealOrderApiController
's POST handler, we create the MealOrder
, but then toss it out once we've asked for the price.
Now that we have a repository, we can use it to store these created orders.
- Open up the
MealOrderApiController
class - Create a default (no-argument) constructor that is empty
- ? Why do you need to do this?
- Create a
private
member variable that will hold a reference to aMealOrderRepository
- Create a new constructor that takes a repository as a parameter and saves it to the member variable
- This is manual dependency injection
- Make sure all tests are still passing.
Before writing any more code, let's write a test that will make sure a new order created via the API stores it in the repository.
Add this test to the MealOrderApiControllerTest
class:
@Test
public void mealOrderIsStoredInRepository() throws Exception {
MealOrderRepository mealOrderRepository = new MealOrderRepository();
MealOrderRequest mealOrderRequest = new MealOrderRequest();
mealOrderRequest.setBurger("none");
MealOrderApiController controller = new MealOrderApiController(mealOrderRepository);
MealOrderResponse response = controller.mealOrder(mealOrderRequest);
assertThat(mealOrderRepository.findAll())
.hasSize(1);
}
C. Save New Order to Repository¶
In the API controller, you'll save the meal order into the repository.
- Open up the
MealOrderApiController
class. - In the
mealOrder()
method, after creating amealOrder
object, use the repository to save the meal order. -
Run the test from above and it should pass. Then run all the tests.
Run All Tests
When you run all the tests, two other tests might fail. Why?
If the two tests,
regularBurgerWithLargeFriesIs10Dollars
andmealOrderBurgerCheeseWithLargeDrinkIs8Dollars
aren't broken, then you're done! -
If the two tests are failing with a
NullPointerException
, you can fix them by always passing in a newMealOrderRepository
when instantiating theMealOrderApiController
, e.g.:MealOrderApiController controller = new MealOrderApiController(new MealOrderRepository());
Question
If the tests were broken, what are some other ways to fix them tests?