spring-boot Webアプリケーションのjpaリポジトリの統合テストに問題があります。 アクセスされたリポジトリが結果を返さないため、サービスメソッドのテストが失敗します。しかし、ログにはテストのトランザクションが開始されたことが示された後、SQLスクリプトが正しく実行されるため、データベースのトランザクションにはデータが含まれている必要があります。Spring JPAリポジトリfindAllはJUnitテストでデータを返しません
コードがWebサービスとして使用されている場合、期待どおりにデータにアクセスできるため、テストのトランザクションに問題があるようです。
誰でもこの問題を解決するための正しい方向を指摘できますか?
PS:@Data
は、https://projectlombok.org/から完全なBeanを作成します。
エンティティ
@Entity
@Data
public class ConcreteEvent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String caption;
private String description;
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime startDate;
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime endDate;
}
リポジトリ
public interface ConcreteEventRepository
extends PagingAndSortingRepository<ConcreteEvent, Long> {
}
サービス
012:ここでは私の対応するコードです
@Service
public class CalenderEventServiceImpl implements CalendarEventService {
@Autowired
private ConcreteEventRepository concreteEventRepository;
@Override
public List<ConcreteEvent> getCalendarEventsForDay(DateTime day) {
List<ConcreteEvent> list = new ArrayList<>();
Iterable<ConcreteEvent> findAll = concreteEventRepository.findAll();
findAll.forEach(list::add);
return list;
}
}
テスト
@ActiveProfiles("test")
@SpringApplicationConfiguration(Application.class)
@WebAppConfiguration
@DirtiesContext
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class CalendarEventServiceTest
extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private CalendarEventService calendarEventService;
@Before
public void initialize()
{
executeSqlScript("classpath:concreteEvents.sql", false);
}
@Test
public void testGetCalendarEventsForDay_UseConcreteEvents() {
List<ConcreteEvent> calendarEventsForDateTime = calendarEventService.getCalendarEventsForDay(new DateTime(2016, 06, 20, 18, 00));
assertNotNull("No list of events retrieved", calendarEventsForDateTime);
assertEquals("Not the correct number of events retrieved", 2, calendarEventsForDateTime.size());
}
}
SQLスクリプト
INSERT INTO CONCRETEEVENT (ID, CAPTION, DESCRIPTION, STARTDATE, ENDDATE) values (1, 'TestEvent1', 'Test Description 1', PARSEDATETIME('2016-06-24 18:00', 'yyyy-MM-dd hh:mm'), PARSEDATETIME('2016-06-24 20:00', 'yyyy-MM-dd hh:mm'));
INSERT INTO CONCRETEEVENT (ID, CAPTION, DESCRIPTION, STARTDATE, ENDDATE) values (2, 'TestEvent2', 'Test Description 2', PARSEDATETIME('2016-06-24 18:15', 'yyyy-MM-dd hh:mm'), PARSEDATETIME('2016-06-24 20:15', 'yyyy-MM-dd hh:mm'));
ログイン
o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [[email protected] testClass = CalendarEventServiceTest, testInstance = [email protected], testMethod = [email protected]ceTest, testException = [null], mergedContextConfiguration = [[email protected] testClass = CalendarEventServiceTest, locations = '{}', classes = '{class api.Application}', contextInitializerClasses = '[]', activeProfiles = '{test}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]]; transaction manager [[email protected]b66ac74]; rollback [true]
o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [api/calendar/service/concreteEvents.sql]
o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [api/calendar/service/concreteEvents.sql] in 7 ms.
o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
o.s.t.c.transaction.TransactionContext : Rolled back transaction for test context [[email protected] testClass = CalendarEventServiceTest, testInstance = [email protected], testMethod = [email protected]ceTest, testException = java.lang.AssertionError: Not the correct number of events retrieved expected:<2> but was:<0>, mergedContextConfiguration = [[email protected] testClass = CalendarEventServiceTest, locations = '{}', classes = '{class api.Application}', contextInitializerClasses = '[]', activeProfiles = '{test}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]].
o.s.w.c.s.GenericWebApplicationContext : Closing org.s[email protected]56620197: startup date [Fri Jun 24 22:50:25 CEST 2016]; root of context hierarchy
設定
HibernateTestConfiguration:
@Configuration
@Profile("test")
public class HibernateTestConfiguration extends HibernateConfiguration {
@Bean
@Override
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setPassword(environment.getRequiredProperty("jdbc.test.password"));
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:dataSource;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
@Override
protected Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "create");
return properties;
}
}
HibernateConfiguration:
@Configuration
@EnableJpaRepositories("api")
@EnableTransactionManagement
@PropertySource(value = { "classpath:application.properties" })
@Profile("default")
public class HibernateConfiguration {
private static final String[] PACKAGES_TO_SCAN = new String[] { "api" };
@Autowired
protected Environment environment;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(PACKAGES_TO_SCAN);
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public DataSource dataSource() {
// stripped for brevity
}
protected Properties hibernateProperties() {
// stripped for brevity
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
AppConfiguration:
@Configuration
@EnableAutoConfiguration
@ComponentScan("api")
@EnableWebMvc
public class AppConfiguration {
}
アプリケーション:
の@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
依存
- 春ブート・スターター・ウェブ:1.3.5
- 春ブート・スターター・データ-JPA:1.3.5
- 春ブートスターターテスト:1.3.5
- スプリングテスト:4.2。6
- 春-ORM:4.2.6
- H2:1.4.191
これが本当にあなたの問題に対する答えであれば、回答を受け入れられた回答としてマークすることができます。 –