title: How to consistently wipe H2 in Memory database when using JPA and JUnit Testing
body: <p>My set up is like this. </p>
  
  <p>H2 in Memory database connected to using JPA the persistence context is configured  using Spring. The database set up script is run by Flyway to generate my tables and add in data.</p>
  
  <p>Database URL: jdbc:h2:mem:test_data</p>
  
  <p>In our JUnit tests we have setUp and tearDown Methods like this</p>
  
  <pre><code>@Override
  protected void setUp() throws Exception {
      this.context = new ClassPathXmlApplicationContext("classpath:/DataContext.xml");
      this.data = this.context.getBean(DataProvider.class);
  }   
  
  @Override
  protected void  tearDown( ) throws Exception {
      this.context.close();
      this.context = null;
      this.data = null;
  }
  </code></pre>
  
  <p>The intention here is for each JUnit test to get it's own data base, and this does seem to work sometimes, however there seem to be occasions when it appears like I am getting the same database as the previous test. An example is that I have 2 tests:</p>
  
  <pre><code>public void testGetFoos()
  {       
      Collection&lt;Foo&gt; foos= data.getFoos();
      assertEquals(NUMBER_OF_FOOS,foos.size());
  }
  
  public void testSaveFoos()
  {       
      Foo bar = makeDummyFoo();
      data.saveFoo(bar);
      Collection&lt;Foo &gt; foos = data.getFoos();
  
      assertEquals(NUMBER_OF_FOOS + 1,foos.size());
  }
  </code></pre>
  
  <p>These methods should be able to run in any order and when running the maven build that appears to be the case, they are able to run independently without affecting each other, however occasionally when running the JUnit test class individually from eclipse the save method will run first, then the get method will run and get the wrong count because it seems to have gotten the same in mem database as the previous test method.</p>
  
  <p>So my question is how to I kill my H2 in memory database between JUnit tests using my set up with Spring? or What could be causing it to not shut down properly, if the context.close() method is the correct way?</p>