I initially just had a Java Servlet that I needed to unit test. I wanted to make sure it would handle requests correctly, so I used Spring’s MockHttpServletRequest in a jUnit test and that method worked great. Very simple unit test.
Now, I want to extend the test and I want to do a series of database transactions and mock http servlet requests to simulate users using the system over a period of time.
I guess I could cram all of this into a single unit test but that doesn’t seem like the right thing to do since it would violate the spirit of a unit test.
So what is the proper way to test a series of events in a particular order like this?
Here’s a stripped down version of what I have so far:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"testContext.xml"})
public class servletTest {
//Injected request
@Resource(name="mockTestServletRequest")
MockHttpServletRequest request;
@Test
public void mockRequest() {
//perform a mock servlet request
}
So do I simulate a timeline of events by just adding more methods annotated with @Test above and below the one I have already ? Am I guaranteed that these methods will be executed in the order listed?
That will be an integration test. Take a look at spring’s testing framework. This means you will start your spring context, and have everything running. You can either use an in-memory database, or a standalone one.
When everything is started, you can inject an instance of a controller of yours and trigger a request, then another one. By default each method is in a transaction, which gets rolled back when the method completes, so don’t worry about polluting the database.