I am starting to write some Unit test with an H2 database.
Therefore, I want to create a table out of my @Entity.
However, I always get the following error message:
12:40:13.635 [main] WARN org.springframework.context.support.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in at.wrk.fmd.config.JpaConfigTest: Bean instantiation via factory method failed;
Table "ROLLETEST" not found; SQL statement:
INSERT INTO RolleTest(created_at, bezeichnung) VALUES (now(), 'ADMIN') [42102-197] java.lang.IllegalStateException: Failed to load ApplicationContext
Here are my classes:
JpaConfigTest
@Configuration
@EnableJpaRepositories
@PropertySource("application.propertiesTest")
@EnableTransactionManagement
public class JpaConfigTest {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1", "sa", null);
new ResourceDatabasePopulator(new ClassPathResource("/import-test.sql")).execute(dataSource);
return dataSource;
}
}
InMemoryDbTest:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = { JpaConfigTest.class },
loader = AnnotationConfigContextLoader.class)
@Transactional
@WebMvcTest
public class InMemoryDbTest {
@Resource
private StudentRepository studentRepository;
@Test
public void givenStudent_whenSave_thenGetOk() {
Student student = new Student(1, "john");
studentRepository.save(student);
List<Student> student2 = studentRepository.findAll();
}
}
application.propertiesTest
server.port=8080
server.error.whitelabel.enabled=false
# H2
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
import-test.sql
INSERT INTO RolleTest(created_at, bezeichnung) VALUES (now(), 'ADMIN');
Maybe someone can tell me what I am missing here.
Sorry, for answering so late, but I have been ill the last couple of days. What I did wrong was that I was not aware of doing an Integration test here. So, some steps had to be done before doing the test itself. I copied the application-test.properties to besides my application.properties file. Then I annotated my main test class as following:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
Then ApplicationContext starts up, creates my tables in my in-memory-database and I can do my tests.
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.