My Springboot project uses MariaDB and JPA works fine in normal mode. When I tried to run my DataJpa JUNIT Tests, there was an error. "The Table Company could not be found (the database is empty)".
This is my application.properties File for my normal database.
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mariadb://localhost:3306/app
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.properties.hibernate.format_sql=true
spring.data.rest.base-path=/app
This is my application-test.properties File for my test database.
# must actually be named application-test.properties ;-)
# Enable H2 console
spring.h2.console.enabled=true
# H2 console path
spring.h2.console.path=/h2-console
# Configure H2 database
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MYSQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
# Configure JPA and Hibernate
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
These are my JUNIT Tests.
package ch.wiss.unternehmensliste.repository;
import ch.wiss.unternehmensliste.model.Company;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.annotation.Rollback;
import java.util.List;
import java.util.Optional;
@DataJpaTest
class CompanyRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
CompanyRepository companyRepository;
/**
* JUnit test for saving a Company
*/
@Test
public void saveCompanyTest(){
Company company = new Company("Microsoft", "www.microsoft.com", "Zürich");
companyRepository.save(company);
Assertions.assertThat(company.getId()).isGreaterThan(0);
}
}