Lab04 dependency injection
Goal¶
Modify the CoffeeOrderApiController
so that you can return coffee order information from the CoffeeOrderRepository
via dependency injection.
Spring Annotation Reference
This reference of annotations might be helpful: http://engineering.pivotal.io/post/must-know-spring-boot-annotations-controllers/
Add Failing Unit Test¶
-
Open
CoffeeOrderApiController
and create a constructor that takes a dependency onCoffeeOrderRepository
as a parameter.- Make sure to save the incoming reference to a member (instance) variable
-
Create a new test class named
CoffeeOrderApiControllerTest
and copy the contents belowpackage com.welltestedlearning.cvm; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class CoffeeOrderApiControllerTest { @Test public void testGetMapping() throws Exception { CoffeeOrderRepository coffeeOrderRepository = new FakeCoffeeOrderRepository(); CoffeeOrder coffeeOrder = new CoffeeOrder(); coffeeOrder.size(SizeOption.MEDIUM); coffeeOrder.setId(123L); coffeeOrderRepository.save(coffeeOrder); CoffeeOrderApiController controller = new CoffeeOrderApiController(coffeeOrderRepository); CoffeeOrderResponse coffeeOrderResponse = controller.coffeeOrderInfo("123"); // medium coffee is 150 cents assertThat(coffeeOrderResponse.getPrice()) .isEqualTo("150"); } }
-
Run this test, which should fail. The next section will make it pass.
Lookup CoffeeOrder ID in Repository¶
-
Open the
CoffeeOrderApiController
class -
In the
coffeeOrderInfo
method, use thecoffeeOrderId
that's passed in to:-
Find the
CoffeeOrder
from theCoffeeOrderRepository
by the id usingfindOne()
-
Convert it to an
CoffeeOrderResponse
and return it
-
-
Run the
CoffeeOrderApiControllerTest
and it should now pass.
Autowire Repository¶
- Add the
@Repository
annotation toFakeCoffeeOrderRepository
so that Spring can find and create it during the automatic dependency injection ("autowire") process.
Sample Data in Repository¶
-
To "pre-load" some coffee order data into the repository, copy the entire file CoffeeOrderDataLoader.java into the production code directory with the other classes.
-
This would be in
src/main/java/com/welltestedlearning/cvm
Add Integration Test¶
Copy the CoffeeOrderRestTest.java file into your src/test/java
directory and run the tests.
If everything is wired properly, it should pass.
Try it Out¶
-
See if you get the data by hitting this URL endpoint:
http://localhost:8080/api/coffeeorders/1
You should see the JSON representation of the CoffeeOrder with ID of
1
and a price. -
Try adding more "sample" data to the
CoffeeOrderDataLoader
'srun()
method and the use your browser to hit the endpoint with different IDs.
Once you've completed the above steps,
check in with the instructor to review your code.