Too many DDL occur when using @DataJpaTest in H2DB

Viewed 65

I changed JUnit4 to JUnit5.

Also previously, testing with MSSQL, but we changed it to H2DB.

The problem occurred at this time.

My legacy project has about 400 tables.

If you conduct a persistence test using @DataJpaTest, occurred more than 400 CREATE DDLs.

I looked for a solution to solve this problem, but the best-looking solution I found was to pre-write about 400 Create DDLs in schema.sql.

What I want.

I want to create a MEMBER table only when there is a code like the following, and test only the MEMBER table.

public interface MemberRepository extends JpaRepository<Member, Long>{
}

Do you have any useful features or solutions for JUnit5?

1 Answers

Create application-test.yml for testing config and set ddl-auto to none.

application-test.yml

spring:
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: none
  

Use @ActiveProfiles("test") to start application-test.yml and @Sql("Member.sql") for Testing script.

@ActiveProfiles("test")
@DataJpaTest
public class MemberRepositoryTests {
    @Autowired
    private MemberRepository memberRepository;

    @Test
    @Sql("Member.sql")
    public void testSomething() {
        Member member = memberRepository.findById(1L).orElse(null);
        assertThat(member).isNotNull();
        assertThat(member.getId()).isEqualTo(1L);
    }
}     

Create the Member.sql to scr/test/resource/com.yourpackage

create table if not exists member (id bigint not null, primary key (id));
insert into member (id) values (1);

In this case, DDLs will not create the table and you can custom your sql to run something on the MemberRepository.

The complete code is here.

Related