Moazzam
Moazzam

Reputation: 429

Loading initial test data in H2 in spring boot

I am using Spring Boot 1.5.8.Release and writing test cases using H2 in memory database. Currently in each test case class, we have @Before annotation, where we insert data using Spring Data classes.

I want to know, can I have a single place in project where we can define data for our all test cases. The database tables are created by Hybernate using entity classes. The only desired thing is about inserting data from single place instead of from @Before in each test case class.

I tried to use data.sql containing Insert statements but with it, Spring does not generate schema objects (tables) due to which I get table not found errors. I do not want to specify Create Table statement for each table in schema.sql

application-test.yml

spring:
  datasource:
    url: jdbc:h2:mem:test;
    driverClassName: org.h2.Driver
    username: sa
    password: 
  jpa:
    database: h2
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create
      naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    properties: 
      hibernate:
        show_sql: true
        format_sql: false

Schema.sql

CREATE SCHEMA AB AUTHORIZATION SA;

AbcControllerTest.java

@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
@SpringBootTest(classes = WebApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class AbcControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @Autowired
  private LeDataService leDataService;

  @Before
  public void setup() {
    MyInfo myInfo = new MyInfo();
    ..............
    ..............
    leDataService.save(myInfo);
  }

  @Test
  public void getAbcTest() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/Abcs/1234567/12345678")
        .with(SecurityMockMvcRequestPostProcessors.user("test").password("test123"))
        .with(SecurityMockMvcRequestPostProcessors.csrf()))
        .andExpect(status().isOk())
  }

}

Upvotes: 4

Views: 7659

Answers (1)

gokhanbirincii
gokhanbirincii

Reputation: 585

create new class annotated with @Component @Profile({ "dev", "test" }) and that implements CommandLineRunner then inject dependencies

Override run() method with your initial data that came with CommandLineRunner

for example

    @Component 
    @Profile({ "dev", "test" })
    setupInitialData implements CommandLineRunner {

    UserService userService;

    //bla bla

    @Override
    @Transactional
    public void run(String... args) {
       User user = new User;
       user.setName("test");
       userService.save(user);

       //bla bla
    }

 }

Upvotes: 2

Related Questions