I’m hitting a strange error related to unit-testing in my Java application.
During unit-testing I use in-memory HSQLDB pre-filled with custom data (via an Insert script triggered automatically) and Hibernate as ORM to access it.
Problem is following, if I start the unit-test on a single class (i.e.: TestDummyClass.java) the db is recreated (from the original insert script) after each method test.
If I launch the unit-test on the whole project (src/test) which contains multiple test classes, the DB is initialize on the beginning for each test-class and not on each test-method.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:com/wizche/app-context-test.xml" })
public class TestDummyClass {
.....
}
This means for example that if in TestDummyClass I change the DB (i.e. creating a new object) in some test-method the new object will stay there for the following test-methods in the same class. Therefore the asserts should differs if I start it on the project or on the single class!
Can someone explain me why is this happening? How can I decide when to restore the clean-db?
NB: I’m using SpringJUnit4ClassRunner with a custom context configuration for the whole test-project (in which there is no parameter related to unit-testing).
NB2: I start JUnit direct in SpringEclipse
The reason is that if you use SpringJUnit4ClassRunner, it tends to cache the application context if you use the exact same location for multiple tests – this caching is across a suite so if you execute all the tests in your project in a single suite, and use the same application context location across multiple tests, it is likely that you will get a cached context – and if you modify beans in a context, that will reflect for other tests too.
A fix is to add
@DirtiesContextannotation to the test class or test method