나는 spring-data-jpa와 DBUnit을 사용하여 Spring 리포지토리 코드의 통합 테스트를 작성하기 위해 Petry Kainulainen이 작성한 매우 유용한 블로그 게시물 인 this을 따라왔다.통합 테스팅 DBUnit을 이용한 스프링 저장소 레이어
는 나는 내 빈 컨텍스트 XML 그렇게
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:property-placeholder location="file:src/main/webapp/WEB-INF/config/application-test.properties"
ignore-resource-not-found="false" />
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
<property name="driverClass" value="${db.driver}" />
<property name="jdbcUrl" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="directorRepository" name="directorRepositoryMock" class="org.mockito.Mockito"
factory-method="mock">
<constructor-arg value="com.tvfreakz.repository.DirectorRepository" />
</bean>
</beans>
내 데이터 집합 XML은 다음
여기<!DOCTYPE dataset SYSTEM "my-dataset.dtd">
<dataset>
<director directorid="1" director="Ridley Scott" />
<director directorid="2" director="James Cameron" />
<director directorid="3" director="David Fincher" />
<director directorid="4" director="Jean-Pierre Jeunet" />
</dataset>
저장소 인터페이스
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.tvfreakz.model.entity.Director;
@Repository("directorRepository")
public interface DirectorRepository extends JpaRepository<Director, Long> {
Director findByDirectorId(Long directorId);
}
에게있어 것처럼 설정 그리고 내 테스트 클래스는있다 그렇게 설정하십시오
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.tvfreakz.model.entity.Director;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/config/testMVCContext.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
@DatabaseSetup("testDataset.xml")
public class ITDirectorRepositoryTest {
@Autowired
private DirectorRepository repository;
@Test
public void testFindByDirectorIdWhenNoDirectorFound() {
Director director = repository.findByDirectorId(10L);
assertNull(director);
}
@Test
public void testFindByDirectorIdWhendirectorIsFound() {
Director director = repository.findByDirectorId(1L);
assertEquals("Ridley Scott", director.getDirectorName());
}
}
@DatabaseSetup
주석은 내 구성을 취하여 dataSource
bean으로 구성된 테스트 데이터베이스에 모든 테이블과 데이터 삽입을 설정해야합니다.
이 작업은 아무 것도 수행하지 않습니다. 즉, 테이블이나 데이터가없는 데이터베이스는 공백으로 남으며 testFindByDirectorIdWhendirectorIsFound
은 반환 된 디렉터가 null이므로 두 번째 테스트가 실패합니다. 내가 뭘 놓치고 있니?
편집 1 확인 일부 진전이 있습니다. 이제 테이블이 생성되었지만 데이터가 없습니다. 문제는 내가 모의 저장소를 사용해서는 안된다는 것입니다. 내 컨텍스트 XML을 다음과 같이 업데이트해야했습니다. 그래서 다음 호 시도하고 데이터
EDIT 내 새로 만든 테이블을 작성하지 않는 이유를 작동하는 2 구동 JpaTransactionManager 콩과 텍사스 주석 컨텍스트에 추가
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:property-placeholder location="file:src/main/webapp/WEB-INF/config/application-test.properties"
ignore-resource-not-found="false" />
<jpa:repositories base-package="com.tvfreakz.repository" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<entry key="hibernate.hbm2ddl.auto" value="update"/>
<entry key="hibernate.format_sql" value="true"/>
<entry key="hibernate.show_sql" value="true"/>
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
<property name="driverClass" value="${db.driver}" />
<property name="jdbcUrl" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
</beans>
EDIT 3 OK 나는 내 maven 종속물에 slf4j를 포함시키고 DEBUG 레벨이 설정된 log4j.properties 파일을 생성 한 후 DEBUG 레벨을 활성화 할 수있었습니다.
그리고 로그에서이 사실을 알 수 있습니까?
14:47:05,670 INFO TestContextManager:242 - Could not instantiate TestExecutionListener [com.github.springtestdbunit.DbUnitTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/dbunit/dataset/IDataSet]
나는이 내 테스트 코드 나는 내 메이븐 POM의 DBUnit를 종속성 누락 된 것 같습니다 원래의 게시물에 편집 한 내용과 함께
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
스프링 데이터 JPA를 사용하고 있습니까? 아니면 다른 지속성 라이브러리/프레임 워크를 사용하고 있습니까? 또한 실제 저장소 대신 모의 저장소를 사용하는 이유가 있습니까? – pkainulainen
@pkainulainen 예 스프링 데이터를 사용하여 jpa, 나는 당신이 뭔가를 모의하고 있다고 생각합니다. 이것은 제 실수 일 수 있습니다. 단지이 이론을 지금 테스트 해보십시오. LocalContainerEntityManagerFactoryBean을 사용하려면 테스트 컨텍스트 XML을 설정해야한다고 생각합니다. – PDStat
@pkainulainen 나는 모의를 사용하는 것이 잘못되었습니다. 내 편집보기, 지금 테이블이 있지만 데이터가 없습니다. – PDStat