title: Play tests with database: "Too many connections"
body: <p>To have a database available in scalatest with evolutions I use this extension of the default <code>PlaySpec</code> inspired by <a href="https://stackoverflow.com/questions/33392905/how-to-apply-manually-evolutions-in-tests-with-slick-and-play-2-4">this SO question</a>:</p>
  
  <pre><code>trait ResetDbSpec extends PlaySpec with BeforeAndAfterAll {
    lazy val appBuilder = new GuiceApplicationBuilder()
    lazy val injector = appBuilder.injector()
    lazy val databaseApi = injector.instanceOf[DBApi]
  
    override def beforeAll() = {
      Evolutions.applyEvolutions(databaseApi.database("default"))
    }
  
    override def afterAll() = {
      Evolutions.cleanupEvolutions(databaseApi.database("default"))
      databaseApi.database("default").shutdown()
    }
  }
  </code></pre>
  
  <p>It applies database evolutions when the suite starts, and reverts them when the suite ends. A test then looks like</p>
  
  <pre><code>class ProjectsSpec extends ResetDbSpec with OneAppPerSuite { ...
  </code></pre>
  
  <p>After adding more tests like this, I hit a point where some tests that succeed when I run them alone, fail with this error:</p>
  
  <blockquote>
    <p>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"</p>
  </blockquote>
  
  <p>As can be see in the code above, I tried to add the line</p>
  
  <pre><code>databaseApi.database("default").shutdown()
  </code></pre>
  
  <p>in <code>afterAll()</code> to mitigate that, but it had no effect. I tried to not run tests in parallel, but no effect either. Where is it that I open db connections without closing them, and where should I call <code>shutdown()</code>?</p>
  
  <p><em>N.B. I use Play 2.5.10 and Slick 3.1.</em></p>