简体   繁体   中英

Testing JPA with Spring Boot 1.4.1 and H2

I'm trying to test my JPA code using H2, my production DB is PostGres.

The error I get right now when I run my test is:

Caused by: java.lang.ClassNotFoundException: org.h2.Driver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)

I do have H2 in my pom.xml file:

<dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>

Not sure why its not finding the driver.

As an alternative, I tried adding @DataJpaTest, which does get me an H2 but I have not been successful in overriding how its configured resulting in FlyWay complaining about existing versions after the test has been ran more than once.

I also tried putting the following in a application.yml (in test/resource) in conjunction with @DataJpaTest to deal with my FlyWay issue, but its ignored with this annotation or not being loaded:

hibernate:
      ddl-auto: create-drop

I would like to either:

  1. Figure out why the driver is not being loaded
  2. Figure out how to tweak the DataSource created by @DataJpaTest
  3. Figure out a better way to configure my test Data Source

Any tips? How have other people configured a situation where production is one type of DB and testing is down with an embedded one?

It turns out I was not using 1.4.1 after all. I still had 1.4.0. I updated to 1.4.1 and did a mvn clean package. Also removed the org.hsqldb dependency. Finally I just used the application.yml in src/main/resources and moved my PostGres dependancy to a profile called 'cloud'. I removed all the other configs having to do with H2. I also removed all my annotations on the JUnit class except for the ones given when the test class is first generated by start.spring.io. Everything just worked worked after that. Could be I screwed up something in my configs, or maybe there was some sort of bug in 1.4.0? At any rate I'm back in business :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM