Updated for Fall 2026
Like onions, ogres, and the OSI networking model, our system has many different layers that build upon each other, gradually adding more and more functionality to build up to the completed system. Consequently, it is imperative that we test each layer of the system, in order, to make sure that each part works before we move on to any parts that build on top of it. For us, this means that we will start by testing the persistence layer of our application.
As discussed in lecture, in CSC 326 we use databases for storage of our data, rather than using simple text, CSV, or XML files. Databases have a great many advantages for information management, including better performance, handling integrity of the data, and enabling safe multi-user access.
Additionally, we use Hibernate as our object-relational mapper (ORM) library. ORMs are libraries which handle going back and forth between Java objects that exist in-memory and records in a database table that are stored for long-term use. We’ll cover Hibernate and its complexities in much more detail later on, but for now the essential point to remember is that it lets you take Java objects, save them to the database, and then retrieve them later on, including updating and deleting them if you want. In CoffeeMaker, the state that gets persisted lives in the entity classes (in the edu.ncsu.csc326.coffee_maker.entity package) and the CRUD operations are provided by the *Repository interfaces (in edu.ncsu.csc326.coffee_maker.repositories). The services layer provides the core coffee maker functionality by working with the *Repository and entity classes.
One caveat for working with databases is that they are explicitly designed for storing data long-term that will persist beyond the lifecycle of a single execution of the application. The reason that this matters is that when you save something into the database, it is, by definition, saved. That means it’s still going to be there when subsequent tests or executions of the application come along. Consequently, you must make sure that your tests are atomic or properly independent — that is, that each test takes into consideration what state it needs the database to be in before running. This may involve explicitly creating some test data that will be used, or explicitly deleting some records that would otherwise get in the way. JUnit set up methods using the @BeforeEach annotation are helpful for resetting the database before each test.
The Test Database
Your tests run against a separate database from the running application, so testing never disturbs the production or system test data. The application uses the coffee_maker schema; the tests use coffee_maker_test.
That configuration lives in src/test/resources/application.properties, and it is committed to the repository — you do not create it. Each setting reads an environment variable with a fallback:
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/coffee_maker_test?createDatabaseIfNotExist=true
spring.datasource.username=${MYSQL_USER:root}
spring.datasource.password=${MYSQL_PASSWORD:}
If your MySQL runs on localhost as root with no password, this works with no editing at all. If you set up MySQL to use a psassword, copy coffee_maker/.env.template to coffee_maker/.env and set only the values that differ on your machine. .env is gitignored, so what you put there stays on your machine — and the same application.properties keeps working for your teammates and for GitHub Actions.
Getting Started
We want to follow our process expectations, so do the following:
- Create an issue for the task of completing the Persistence Testing Workshop.
- Create a branch off
developmentfor working on the Persistence Testing Workshop. - Switch to the branch.
We will focus on testing the Recipe requirements. Review the requirements to better understand the tests.
Testing the Persistence Layer
A test class RecipeRepositoryTest has been created for you in the edu.ncsu.csc326.coffee_maker.repositories package. Since the entity classes are POJOs and the *Repository interfaces extend JpaRepository, most of the functionality related to this layer of the system is handled through Spring and Hibernate libraries. But we should do some sanity checking that we can create a Recipe object and write it to the database using the corresponding RecipeRepository. Since RecipeRepository also adds a specific method for getting a Recipe by name, we should ensure that method works correctly.
InventoryRepositoryTest is provided complete as a reference. Read it alongside this page — every pattern you need for the recipe tests is demonstrated there. Inventory is treated as a singleton: the system holds exactly one inventory row, which is why its @BeforeEach empties the table and inserts a single Inventory. Recipes are a collection, so RecipeRepositoryTest sets up two of them.
Neither test class assumes a particular id value. Hibernate generates ids, and which numbers it hands out is not something your tests should depend on. Both classes capture the object they saved and look it up with findById(saved.getId()) when they need it back.
RecipeRepositoryTest Walkthrough
The test class is annotated with @DataJpaTest, which loads only the functionality needed to test the persistence layer. The @AutoConfigureTestDatabase annotation tells Spring to use the test database configured in src/test/resources/application.properties rather than substituting an in-memory embedded database.
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
class RecipeRepositoryTest {
In the test class we @Autowired a reference to RecipeRepository, which gives us an instance for handling database operations, and a TestEntityManager, which we will use in the next section.
@Autowired
private RecipeRepository recipeRepository;
/** Reference to EntityManager */
@Autowired
private TestEntityManager testEntityManager;
The @BeforeEach method sets up for each test case by 1) deleting the current contents of the recipes table, 2) creating two recipes and saving them, and 3) flushing and clearing the persistence context.
Note that the Recipe constructor used here does not include the id. Recent versions of Hibernate require that tests do not supply values for automatically generated fields, so focus on the state of the object rather than its id.
@BeforeEach
public void setUp() throws Exception {
recipeRepository.deleteAll();
recipe1 = new Recipe("Coffee", 50, 3, 0, 0, 0);
recipe2 = new Recipe("Latte", 100, 3, 2, 1, 0);
recipeRepository.save(recipe1);
recipeRepository.save(recipe2);
testEntityManager.flush();
testEntityManager.clear();
}
Why flush() and clear()
Those last two lines are the most important part of this workshop, and they are easy to leave out.
Hibernate keeps a persistence context, which is an in-memory cache of the objects it is managing. When you call save() and then immediately ask the repository for that object, Hibernate can hand you the same Java object you just saved, without ever going to the database. A test written that way passes whether or not a single row reached MySQL. It looks like a persistence test and tests nothing.
The two calls prevent that:
flush()pushes the pending SQL to the database now, rather than whenever Hibernate decides to.clear()empties the persistence context, so the next lookup has no cached object to return and must actually query.
The provided testUpdateInventory shows the full pattern — change the object, save, flush, clear, then re-read and assert on what came back:
Inventory fetchedInventory = inventoryRepository.findById(inventory.getId()).orElseThrow();
fetchedInventory.setCoffee(13);
...
inventoryRepository.save(fetchedInventory);
testEntityManager.flush();
testEntityManager.clear();
Inventory updatedInventory = inventoryRepository.findById(inventory.getId()).orElseThrow();
assertAll("Inventory contents",
() -> assertEquals(13, updatedInventory.getCoffee()),
...);
Asserting on the object save() returns would only re-check fields you just set on an in-memory object. Any time a test writes to the database and then reads back, flush and clear in between.
The Provided Test - Find by Name
RecipeRepositoryTest comes with one completed test, which finds the Latte recipe by name. It calls recipeRepository.findByName(), which returns an Optional<Recipe>. Calling .orElseThrow() gives you the Recipe if the query found one, and fails the test with a clear error if it did not. From there we check the contents with assertAll(), which reports every failing field rather than stopping at the first one.
@Test
public void testFindRecipeByName() {
Recipe fetchedRecipe = recipeRepository.findByName("Latte").orElseThrow();
assertAll("Recipe contents",
() -> assertEquals("Latte", fetchedRecipe.getName()),
() -> assertEquals(100, fetchedRecipe.getPrice()),
() -> assertEquals(3, fetchedRecipe.getCoffee()),
() -> assertEquals(2, fetchedRecipe.getMilk()),
() -> assertEquals(1, fetchedRecipe.getSugar()),
() -> assertEquals(0, fetchedRecipe.getChocolate()));
}
Use this test as the model for the ones you write.
Your Tasks
RecipeRepositoryTest contains three empty test methods marked @Disabled, each with a TODO describing what it needs to do. Implement all three.
| Test | What it should do |
|---|---|
testGetAllRecipes |
Assert that findAll() returns both recipe1 and recipe2 |
testUpdateRecipe |
Change a field on recipe1, save, then flush/clear and read it back |
testDeleteRecipe |
Delete recipe2, then assert that findByName() returns an empty Optional |
Delete the @Disabled annotation from each test as you implement it. A @Disabled test is skipped, not run — if you leave the annotation in place, your finished test never executes and the build stays green while proving nothing.
A few hints:
- For
testUpdateRecipe, follow thetestUpdateInventorypattern above. This is the test that will silently pass for the wrong reason if you skip the flush and clear. - For
testDeleteRecipe,assertTrue(recipeRepository.findByName("Latte").isEmpty())checks that the query came back with nothing. Note the contrast with.orElseThrow()— here an emptyOptionalis the expected result, not a failure. - Also confirm the recipe you did not delete is still there. A delete test that only checks what disappeared will not notice if you deleted everything.
Run Tests
Run your tests and make sure they all pass. Then run them again with coverage — right click src/test/java and select Run ‘All Tests’ with Coverage.
Milestone 1 asks for 60% statement coverage and 50% branch coverage across the Inventory* and Recipe* classes. You are not expected to reach that after this workshop alone; the service and API workshops exercise the same classes from higher layers and will bring the numbers up. Check where you are now so you know how much is left.
Integrate
Your new tests should be passing. It’s time to do the following:
- Commit the changes on your persistence testing workshop branch.
- Create a pull request to merge the persistence testing workshop branch to the
developmentbranch. - Approve the merge request and ensure that the tests are building on GitHub via GitHub Actions.
