JUnit: Looking for communication path between @before method and individual test method

181 views Asked by At

Is there a Java test library which supports the following scenario?

Assume, you have to write web browser tests for a database-based web application (e.g. using Selenium) . A typical test will have the following workflow:

  • Insert test data to DB
  • Run the test logic (open web browser, navigate somewhere, manipulate something, validate if correct things are displayed, validate if DB state changed correctly)
  • Clear the DB

Especially in case of this kind of integration test, you often will require a complex set of diverse objects just to just run the web application (e.g. you need a user account, business-related stuff like products, oders, ...). To keep the tests independent of each other and being able to run the tests in parallel, you want to create this object network for each test, probably with pseudo-random object attributes like user.name="user_123".

Now, in my opinion, a good place to do things you have to repeat for each test, is a @Before-annotated method. However, if the @Before method inserts a DB state, the test method won't know how to access this state, e.g. how to find the user object the @Before method created. It would be nice to have a kind of test method context, which is setup by the @Before method and can be used by the test method.

I thought about implementing something like this on my own, maybe a simple static hashmap with the test method name as key, but probably there already is a library which provides this feature and you know about it ;-) .

2

There are 2 answers

0
Vitaliy On

You are practically there. In fact, we use the exact same technique for integration tests in our product (HP ALM).

In your test class, store whatever tokens generated by the @Before method in members and use them in the tests.

In order not repeat this for each and every integration test class, we defined a base class that contains all the context and the initialization logic and we simply extend with test code.

This base class can in tern extend any other test infra that you may be using (such as AbstractJUnit4SpringContextTests).

4
venergiac On

rainer198, instead of "Clear the DB" you can rollback the tx. I use this way to solve the issue, it is more clean, but, obviously, it depende from your behavior.

On spring I use

@Transactional //This annotation tells the Spring test runner to always roll back each transaction it creates.
@TransactionConfiguration(defaultRollback = true)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/spring/common-main-test.xml")