3
votes

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.

1
Looks to me like the error message is telling you there is no table named ROLLETEST (case is ignored), yet you try to insert into it. Have you created the table?O.O.Balance

1 Answers

2
votes

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.