We have a bit of setup/initialization code we need to do before we can get started. We have seen all of this code before in Tutorial 1. The difference here is that we are going to work though some refactorings to get to where we were in tutorial 1. Here are the various parts:
Configure the Logger
Create the Entity Manager Factory
Create the Entity Manager
Create Entities
Use the Entity Manager
Perform a Query and Verify it Works
The Whole Thing
Here’s all of this put together. Note that we’re going to refactor this heavily coming up.
Get it Running
After creating your Test Class, verify that it runs and that this test passes:
Right-click anywhere in your class’ editor pane.
Select Run As:JUnit Test
title: Tutorial_2_Second_Example
—
There are several things for which we need some support code:
Per test method setup
Per test method cleanup
One-time logger initialization
Inserting a single record
Before putting all of this together, let’s examine each of these things.
Per test method setup
This creates two fields. We then use the JUnit 4 @Before annotation to initialize that before the execution of each individual unit test. For details, please see here.
Per test method cleanup
This example uses the JUnit 4 @After annotation to cleanup up resources we’ve allocation after the execution of each individual unit test. For details, please see here.
One-time logger initialization
This example uses the JUnit 4 @BeforeClass annotation to perform one-time initialization for the whole class. For details, please see here.
In this case, the first line in the method performs basic configuration of the Log4J logging system. The second line sets the default logging level for any class whose package starts with org to ERROR. This significantly reduces the output. It is possible to reduce the output one level further by setting it to FATAL.
Inserting a single record
Rewrite and New Method
With these changes in hand, we can rewrite the previous test method as follows:
Here’s a second test to justify all of this refactoring.
Putting it all Together
And finally, here’s all of the above changes together in one place.
Comments