简体   繁体   English

使用内存db进行Spring Boot测试

[英]Spring Boot testing using in memory db

I have created a Spring web project using Spring Boot. 我使用Spring Boot创建了一个Spring Web项目。 Would like to understand the practice around testing. 想了解一下测试的做法。 I require an in memory embedded database say hsql or h2 for my junits with initial schema.sql. 我需要一个内存嵌入式数据库说hsql或h2用于初始schema.sql的junits。 And on the main application the database could be say mysql or oracle 在主应用程序上,数据库可以说是mysql或oracle

In a non Spring Boot project, we would normally have a separate applicationcontext.xml one which is referred by the web app and for testing we would use applicationContext-text.xml 在非Spring Boot项目中,我们通常会有一个单独的applicationcontext.xml,它由Web应用程序引用,为了测试,我们将使用applicationContext-text.xml

Now, in Spring boot as everything is created automatically and Spring Boot is opiniated too. 现在,在Spring启动时,所有内容都是自动创建的,Spring Boot也是如此。 Would like to know how do I setup having an embedded inmemory db for Junits and an external db like MySQL for the application. 想知道如何为应用程序设置嵌入式内存db for Junits和外部数据库(如MySQL)。

One solution I can think of is using Profiles. 我能想到的一个解决方案是使用Profiles。 with 2 properties file application.properties and application-test.properties. 使用2个属性文件application.properties和application-test.properties。 and use test profile for my junits. 并为我的junits使用测试配置文件。

Any recommendation on the approach I should take. 关于我应采取的方法的任何建议。

A profile is, indeed, the recommended approach. 实际上,配置文件是推荐的方法。 What I would do is probably make the in-memory implementation the "default" profile (it's harmless, in the sense that you never change any real data, so it's better to make that the default in case someone accidentally runs it against a real database). 我要做的可能是将内存中的实现设置为“默认”配置文件(它是无害的,从某种意义上说,你永远不会更改任何真实数据,因此最好将其作为默认设置,以防有人意外地在实际数据库中运行它)。 Personally, I prefer to put all the external configuration in a single application.yml file, but that's really up to you. 就个人而言,我更喜欢将所有外部配置放在一个application.yml文件中,但这完全取决于您。 In the external configuration you need to supply a valid driver class and URL, eg 在外部配置中,您需要提供有效的驱动程序类和URL,例如

spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:test;MODE=PostgreSQL
    schema: classpath:/schema.sql

---

spring:
  profiles: local
  datasource:
    url: jdbc:postgresql://localhost/test
    username: root
    password: changeme
    driverClassName: org.postgresql.Driver
    schema:

(Note that H2 has a postgres compatibility mode, so it is really nice as a complement to postgres in production.) (请注意,H2具有postgres兼容模式,因此它非常适合作为postgres的补充。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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