I am using Postgres database and I want to use H2 database for tests. The problem is when I'm creating new object in database, it seems that H2 is not used at all in test.
Test class:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WithMockUser(roles = "ADMIN")
@ActiveProfiles("test")
public class CompanyTests {
@SpyBean
private CompanyService companyServiceMock;
@Autowired
private MockMvc mockMvc;
@Autowired
EntityManager entityManager;
@Test
@Transactional
public void testaaaa() {
entityManager.persist(new Company("nnnn", new Address()));
List<Company> all = companyServiceMock.findAll();
all.forEach(company -> System.out.println(company.getName()));
}
application.properties:
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/EDI
spring.datasource.username=postgres
spring.datasource.password=password
spring.datasource.platform=postgresql
spring.datasource.initialize=true
spring.datasource.continue-on-error=true
spring.jackson.serialization.fail-on-empty-beans=false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
application-test.properties:
spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-
1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
And when I use findAll() in my test, it lists all companies from postgresql and new which is created by entityManager.
您应该为dev
和test
配置文件使用单独的属性文件,在这种情况下,应将application.properties
重命名为application-dev.properties
并仅使用一个属性spring.profiles.active=dev
创建application.properties
文件。
How about adding @TestPropertySource(locations= "classpath:application-test.properties")
to the annotation? you should make it explicit for the test class that you are using the test application.properties .
This is late, but I'd be happy to be of some help.
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.