2017-09-25 13 views
0

H2 데이터베이스에서 통합 테스트를 실행할 때 정의되지 않은 것처럼 보이는 Java 코드에서 호출 된 사용자 정의 함수가 MS SQL Server에 있습니다. 내 코드는 the previous question에 있습니다.DbUnit - JdbcSQLException : "*"함수를 찾을 수 없음

테스트 코드 :

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {H2Config.class}) 
@TestExecutionListeners({ 
     DependencyInjectionTestExecutionListener.class, 
     DbUnitTestExecutionListener.class, 
     TransactionalTestExecutionListener.class 
}) 
@TransactionConfiguration(defaultRollback = true) 
public class TableDaoTest { 

    @Autowired 
    private TableDao tableDao; 

    @Test 
    @DatabaseSetup("/datasets/import.xml") 
    public void testMethod01() { 
     tableDao.getRecordsByGroup(); 
     ... 

데이터베이스 스키마가 Hibernate에 의해 자동 생성됩니다. 보시다시피 테스트 데이터는 xml 데이터 세트를 사용하여 DbUnit에 의해 채워집니다. 그리고 MS SQL 서버 DB에 존재하는 함수가 H2 데이터베이스에서 정의되지 않았기 때문에이 테스트는 실패합니다.

응용 프로그램 로그 :

Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement 
    ... 
Caused by: org.h2.jdbc.JdbcSQLException: Function "SAFE_MOD" not found; SQL statement: 
    select table10_.id, table10_.value, ... from Table1 table10_ where table10_.group1=dbo.safe_mod(?, ?); 
    ... 

방법 DbUnit을 테스트하기 전에 함수를 작성/가져?

답변

0

H2 데이터베이스는 사용자 정의 SQL 함수를 지원하지 않습니다. 그러나이 데이터베이스에서는 Java 함수를 저장 프로 시저로 사용할 수도 있습니다.

@SuppressWarnings("unused") 
public class H2Function { 
    public static int safeMod(Integer n, Integer divider) { 
     if (divider == null) { 
      divider = 5000; 
     } 

     return n % divider; 
    } 

} 

정적 Java 메소드 만 지원됩니다. 수업과 방법 모두 공개해야합니다. 사용하기 전에 기능 (데이터베이스에 등록) CREATE ALIAS ... FOR를 호출하여 선언해야

자바 :

CREATE ALIAS IF NOT EXISTS safe_mod DETERMINISTIC FOR "by.naxa.H2Function.safeMod"; 

이 문장은 어떤 시험 전에 실행되어야한다 그래서 연결 초기화 SQL 안에 넣어하기로 결정 :

@Bean 
public DataSource dataSource() { 
    BasicDataSource dataSource = new BasicDataSource(); 

    dataSource.setDriverClassName("org.h2.Driver"); 
    dataSource.setUrl("jdbc:h2:mem:my_db_name"); 
    dataSource.setUsername("sa"); 
    dataSource.setPassword(""); 
    dataSource.setConnectionInitSqls(Collections.singleton(
     "CREATE ALIAS IF NOT EXISTS safe_mod DETERMINISTIC FOR \"by.naxa.H2Function.safeMod\";")); 

    return dataSource; 
}