Skip to main content

Updated for Fall 2026

Now that we’ve tested some of the persistence functionality, let’s move up the stack and test the service layer. The service layer is where our application does most of its work. We’ll focus on testing the RecipeService interface through its RecipeServiceImpl implementation.

InventoryServiceTest is provided complete as a reference for this layer. Read it alongside this page. Inventory is treated as a singleton — the system holds exactly one inventory row — which is why its @BeforeEach empties the table before each test. Recipes are a collection, so your tests will set up more than one.

Transactions, @Transactional, and EntityManager

It is best practice, and used throughout here, to run tests within a database transaction. For relational databases like ours, a transaction represents a “unit of work” that is executed all together in one go. At the end of the test, Spring “rolls back” the transaction, discarding everything the test did. That is what keeps one test from polluting the next.

Three things about this layer differ from the persistence workshop, and getting them wrong is the most common way these tests go sideways.

@Transactional goes on the class. In InventoryServiceTest it annotates the test class, not each method, so every test in the class runs inside a transaction that is rolled back afterwards.

@SpringBootTest does not give you a TestEntityManager. That is a @DataJpaTest convenience. Here you inject the standard jakarta.persistence.EntityManager instead:

@Autowired
private EntityManager entityManager;

flush() and clear() matter more here, not less. Inside a single transaction, nothing is written to the database until something forces it. If you assert without flushing and clearing, you are checking Hibernate’s in-memory persistence context, not what was actually saved — the test passes whether or not the data reached MySQL. Refer back to Why flush() and clear() for the full explanation.

The rule for this workshop: after you call a service method that writes, flush, clear, and then read the data back through the service before asserting on it.

Getting Started

We want to follow our process expectations, so do the following:

  • Create an issue for the task of completing the Service Testing Workshop.
  • Create a branch off development for working on the Service Testing Workshop.
  • Switch to the branch.

We will focus on testing the Recipe requirements through the methods RecipeService provides. Review the requirements to better understand the tests.

Service Layer Testing

Create a new RecipeServiceTest class. In IntelliJ, open RecipeService in the editor, put your cursor in the RecipeService class name then use Navigate > Test (Ctrl+Shift+T, or Cmd+Shift+T on macOS) and select Create New Test…. In the dialog:

  • Testing library: JUnit5
  • Class name: RecipeServiceTest
  • Check setUp/@Before to generate a setup method
  • You can check the RecipeService methods you plan to test to generate stubs for them

The test class is created in coffee_maker/src/test/java under the same package as RecipeService.

Now add the annotations that set up Spring testing. @SpringBootTest starts the application context so the real service and its dependencies are available. @Transactional wraps each test in a transaction that gets rolled back.

The @Autowired fields use Spring’s dependency injection to hand you a working RecipeService — the implementation talks to the recipes table through RecipeRepository, but your test does not need to know that. Testing the service through its own interface is the point; if a test reaches for the repository to check its work, it is testing two layers at once.

@SpringBootTest
@Transactional
public class RecipeServiceTest {

	/** Reference to RecipeService (and RecipeServiceImpl). */
	@Autowired
	private RecipeService recipeService;

	/** Reference to EntityManager */
	@Autowired
	private EntityManager entityManager;

Depending on the state the database is in, tests can seem to fail inexplicably if unexpected values are present. Clear the recipes table before each test. InventoryServiceTest does this with a JPQL bulk delete through the EntityManager it already has, which avoids injecting the repository just to clean up:

/**
 * Sets up the test case.
 * @throws java.lang.Exception if error
 */
@BeforeEach
public void setUp() throws Exception {
	entityManager.createQuery("DELETE FROM Recipe").executeUpdate();
}

(Note: in a production system you would never do this, because you would be deleting the data you care about. We avoid that by running against a separate test database. See The Test Database.)

Test Add Recipe

We’ll start with testCreateRecipe(), which tests RecipeService.createRecipe(). If you didn’t generate the method, declare it public void and add the @Test annotation. You do not need @Transactional on the method — it is already on the class.

Since the parameters to RecipeService are RecipeDto objects, create a RecipeDto with reasonable values. Use the constructor that does not take an id; ids are generated by Hibernate and your tests should not supply or depend on them.

@Test
public void testCreateRecipe() {
	RecipeDto recipeDto = new RecipeDto("Coffee", 50, 2, 1, 1, 0);

	recipeService.createRecipe(recipeDto);
}

Now the important part. createRecipe() returns a RecipeDto, and it is tempting to assert on that returned object — but doing so only re-checks values you just set on an in-memory object. It would pass even if nothing was written. Instead, flush the pending work, clear the persistence context, and read the recipe back through the service:

@Test
public void testCreateRecipe() {
	RecipeDto recipeDto = new RecipeDto("Coffee", 50, 2, 1, 1, 0);

	recipeService.createRecipe(recipeDto);

	//Read the recipe back through the service rather than asserting on the object
	//createRecipe() returned, so the assertions check what was saved.
	entityManager.flush();
	entityManager.clear();

	RecipeDto createdRecipe = recipeService.getRecipeByName("Coffee");
	assertAll("Recipe contents",
			() -> assertEquals("Coffee", createdRecipe.getName()),
			() -> assertEquals(50, createdRecipe.getPrice()),
			() -> assertEquals(2, createdRecipe.getCoffee()),
			() -> assertEquals(1, createdRecipe.getMilk()),
			() -> assertEquals(1, createdRecipe.getSugar()),
			() -> assertEquals(0, createdRecipe.getChocolate()));
}

Note what is not asserted: the id. The table auto-increments, so the value depends on what ran before, and a test that checks it is testing Hibernate rather than your code. Assert on state.

assertAll() runs every assertion and reports all of the failures, rather than stopping at the first one — which tells you much more when a test breaks.

Run your test to see if it passes. It should! If not, work with the TA to debug it.

Your Tasks

Finish testing RecipeService. The interface provides seven methods:

Method What your test should establish
createRecipe Worked example above
getAllRecipes Create two recipes; assert both come back
updateRecipe(Long, RecipeDto) Change a field, update, then flush/clear and read it back. This is the test that silently passes for the wrong reason if you skip the flush and clear
deleteRecipe(Long) Assert the deleted recipe is gone and that another recipe is still there. A delete test that only checks what disappeared will not notice if you deleted everything
isDuplicateName Cover both a name that exists and one that does not
getRecipeById May be covered through the tests above
getRecipeByName May be covered through the tests above

You can skip dedicated test methods for getRecipeById() and getRecipeByName() if you use them while testing the other functionality, as the worked example above does.

Run Tests

Run your tests and make sure they all pass. Then run them again with coverage by right clicking src/test/java and selecting Run ‘All Tests’ with Coverage.

Milestone 1 asks for 60% statement coverage and 50% branch coverage across the Inventory* and Recipe* classes. Testing RecipeServiceImpl thoroughly should move you a good way toward that; the API workshop exercises the same classes from the layer above and will bring the numbers up further.

Integrate

Your new tests should be passing. It’s time to do the following:

  • Commit the changes on your service testing workshop branch.
  • Create a pull request to merge the service testing workshop branch to the development branch.
  • Approve the merge request and ensure that the tests are building on GitHub via GitHub Actions.

Onward!

Onward to API testing!