springboot~Profile開發環境與單元測試用不一樣的數據庫

指望

  1. 但願開發環境dev用mysql
  2. 單元測試使用本機的h2數據庫

引入依賴

compile('org.springframework.boot:spring-boot-starter-data-jpa')
    runtime('com.h2database:h2')
    runtime('mysql:mysql-connector-java')

兩種環境的配置,默認爲dev

spring:
  application.name: lind-productCenter
  profiles.active: dev

  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
    virtual-host: pilipa
server:
 port: 9090
---
spring:
  profiles: dev
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/productCenter?useSSL=false&allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
      database: MYSQL
      show-sql: true #顯示後臺處理的SQL語句
      hibernate:
        ddl-auto: update #自動檢查實體和數據庫表是否一致,若是不一致則會進行更新數據庫表

---
spring:
  profiles: test
  datasource:
        platform: h2
        driverClassName: org.h2.Driver
        url: jdbc:h2:mem:testdb
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update

單元測試能夠提出一個基類,添加註解便可

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class BaseControllerTest {
  @Autowired
  protected WebTestClient http;

  /**
   * action 執行前運行 .
   */
  @Before
  public void before() {
    http = http.mutate()
        .responseTimeout(Duration.ofMillis(300000))
        .build();
  }

}
相關文章
相關標籤/搜索