In the recipe Creating integration tests for persistent entities, we saw how Spring Roo helps with the creation of integration tests. In this recipe we look at how Spring Roo simplifies the generation of a mock test for an entity using the test
mock
command.
Exit the Roo shell and delete the contents of the C:
oo-cookbookch02-recipes
directory.
Execute the ch02_jsr303_fields.roo
script. It creates a flight-app
Roo project and sets up Hibernate as the persistence provider using the persistence
setup
command. The script also creates a Flight
entity, which has FlightKey
as its composite primary key class, and adds fields to the Flight
and FlightKey
classes. If you are using a different database than MySQL or your connection settings are different from what is specified in the script, then modify the script accordingly.
Start the Roo shell from the C:
oo-cookbookch02-recipes
directory.
Follow these steps to create mock tests:
Flight
entity, using the focus
command:roo> focus --class ~.domain.Flight
Flight
entity, execute the following test
mock
command:~.domain.Flight roo> test mock Created SRC_TEST_JAVAsample ooflightappdomainFlightTest.java
The execution of the test
mock
command creates a JUnit test, FlightTest.java
, which is responsible for mock testing of the Flight
entity, as shown here:
package sample.roo.flightapp.domain; @RunWith(JUnit4.class) @MockStaticEntityMethods public class FlightTest { @Test public void testMethod() { int expectedCount = 13; Flight.countFlights(); ..AnnotationDrivenStaticEntityMockingControl. expectReturn(expectedCount); ..AnnotationDrivenStaticEntityMockingControl.playback(); org.junit.Assert.assertEquals(expectedCount, Flight.countFlights()); } }
If you are using Spring Roo 1.1.3, then you'll have to add the @MockStaticEntityMethods
and @RunWith(JUnit4.class)
annotations in Roo-generated mock tests, as shown.
In the code listing, the @MockStaticEntityMethods
annotation represents a Spring annotation which supports mock testing of static entity methods, like count and finder methods. Spring defines an AnnotationDrivenStaticEntityMockingControl
aspect, which applies to methods of a test class annotated with @MockStaticEntityMethods
and mocks calls to the static
methods of the persistent entity. Additionally, the AnnotationDrivenStaticEntityMockingControl
aspect defines the expectReturn
and playback
methods to simplify writing mock tests.
As the AnnotationDrivenStaticEntityMockingControl
aspect applies to any class annotated with @MockStaticEntityMethods
, it makes it possible to write tests using any testing framework (JUnit or TestNG) for mock testing entities. For testing of instance methods defined in the entity, you'll continue to use the common approaches for mock testing using EasyMock, Mockito, and so on.
52.15.176.80