Skip to content

exercise_01

Frey, Gregor Karl edited this page Nov 1, 2017 · 1 revision

Exercises

Exercise 1: Implement and Test Service Class

Spring Goals

  • Define Spring beans in Java code using the @Bean annotation on factory methods.
  • Understand the way how Spring injects dependencies.
  • Learn to use Spring to set up the context of an unit test.

Other Goals

  • Apply the design patterns of Model, Repository and Service objects.
  • Understand the difference of mock objects for the scope of tests.

Start with git tag exercise_01_start.

Step 1

Implement ShowService.

  • Create ShowService constructor with CinemaRepository, MovieRepository, and Show Repository as parameters. Store references of these repositories in private fields of the class.
  • Create a static factory method in the ShowFull class, that builds a new ShowFull instance from a given show.
  • Implement the service methods.

Step 2

Define Spring context.

  • Complete the definition of stores, repositories, and services as Spring beans in the inner TestConfiguration class of the ShowServiceTest class. Each repository gets the respective store injected, the show service the needed repositories.
  • Create private fields for stores, repositories, and services. Use the @autowire annotation to get the corresponding beans injected by Spring.

Step 3

Define test data.

  • Use the set-up method to define test data, that is reused across all the tests.

Step 4

Implement tests.

  • Implement tests for all methods of the ShowService class.
    • If required, set up required preconditions. For example load the test data into the stores.
    • Execute the service methods.
    • Check the results. Consider using the assertJ library.
    • Make sure the execution of the tests do not interfere with each other. For example clean up the stores.

Run the tests. In case of failures fixe the service implementation (or the tests) until everything runs green.

Extension 1

Exchange the "real" stores and repositories by mocked counterparts.

  • Remove the Spring context and all Spring annotations from the test class.
  • Annotate the test class with @RunWith(MockitoJUnitRunner.class).
  • Annotate the repositories with @Mock.
  • Construct the show service with the mocked repositories.
  • Configure the mocked repositories with the desired behaviour.
  • Adapt the assertions where required.

Hint: This tutorial contains useful examples for using Mockito. Of special interest are the Hamcrest Captures, by which the content of arguments, handed over to method calls of mock objects, can be "captured" and inspected.

Clone this wiki locally