【问题标题】:Spring Boot JPA Test fails with java.lang.IllegalArgumentExceptionSpring Boot JPA 测试因 java.lang.IllegalArgumentException 而失败
【发布时间】:2017-11-29 12:36:56
【问题描述】:

我正在尝试测试我的 JPA 存储库接口。这是一个简单的 Spring Boot Web 应用程序,用于上传和处理 CSV 文件。以下是我需要测试的存储库。

package bloombergfx.data;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import bloombergfx.model.CSVFile;

@Repository
public interface CSVFileRepository extends JpaRepository<CSVFile, Long> {

    CSVFile findByFileName(String fileName);

    <S extends CSVFile> S save(S file);
}

我为测试上述存储库而创建的测试类。

package bloombergfx.data;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Date;

import javax.transaction.Transactional;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;

import bloombergfx.model.CSVFile;
import bloombergfx.model.InvalidRecord;
import bloombergfx.model.Record;
import bloombergfx.model.ValidRecord;

@RunWith(SpringRunner.class)
@DataJpaTest(showSql = true)
@Transactional
public class CSVFileRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private CSVFileRepository csvFileRepository;

    private CSVFile file;

    @Before
    public void setup() {
        CSVFile file = new CSVFile();
        file.setFileName("test_file");
        file.getValidRecords().add((ValidRecord) new Record(1, "USD", "AED", new Date(), 100.00, file).validate());
        file.getInvalidRecords().add((InvalidRecord) new Record(2, "USD", "USD", new Date(), 100.00, file).validate());
    }

    @Test
    public void testFindByFileName() {
        entityManager.persist(file);
        entityManager.flush();

        CSVFile found = csvFileRepository.findByFileName(file.getFileName());

        assertThat(found).isEqualTo(file.getFileName());
    }

    @Test
    public void testSaveS() {
        CSVFile saved = entityManager.persist(file);
        entityManager.flush();

        assertThat(saved).isEqualTo(file);
    }
}

我已使用以下 gradle 设置进行测试。

testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("com.h2database:h2")

当我运行测试时,出现以下错误。

2017-11-29 16:19:08.993  INFO 10968 --- [           main] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@3d299e3 testClass = CSVFileRepositoryTest, testInstance = bloombergfx.data.CSVFileRepositoryTest@3a079870, testMethod = testFindByFileName@CSVFileRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@55a561cf testClass = CSVFileRepositoryTest, locations = '{}', classes = '{class bloombergfx.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@3b938003 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1a8a8f7c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@42f93a98, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@7ce6a65d, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@cb5211d5, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@63440df3], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@62c72501]; rollback [true]
2017-11-29 16:19:09.055  INFO 10968 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@3d299e3 testClass = CSVFileRepositoryTest, testInstance = bloombergfx.data.CSVFileRepositoryTest@3a079870, testMethod = testFindByFileName@CSVFileRepositoryTest, testException = java.lang.IllegalArgumentException: attempt to create create event with null entity, mergedContextConfiguration = [MergedContextConfiguration@55a561cf testClass = CSVFileRepositoryTest, locations = '{}', classes = '{class bloombergfx.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@3b938003 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1a8a8f7c, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@42f93a98, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@7ce6a65d, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@cb5211d5, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@63440df3], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-11-29 16:19:09.074  INFO 10968 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@543588e6: startup date [Wed Nov 29 16:19:04 GST 2017]; root of context hierarchy
2017-11-29 16:19:09.089  INFO 10968 --- [       Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

TestEntityManager 尝试持久化数据时发生错误。

【问题讨论】:

    标签: java spring jpa spring-boot spring-data-jpa


    【解决方案1】:

    您应该编辑@Before 方法的第一行,使其显示为:

    @Before
    public void setup() {
        file = new CSVFile();
        file.setFileName("test_file");
        file.getValidRecords().add((ValidRecord) new Record(1, "USD", "AED", new Date(), 100.00, file).validate());
        file.getInvalidRecords().add((InvalidRecord) new Record(2, "USD", "USD", new Date(), 100.00, file).validate());
    }
    

    目前您正在使用一个局部变量并操作这个局部变量。实例变量file 从未设置过,因此您试图保留一个空对象,这当然是行不通的。

    【讨论】:

    • 非常感谢您的及时答复。我为这个愚蠢的错误挣扎了大约一个小时。
    猜你喜欢
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2019-05-01
    • 2012-10-03
    • 2022-01-15
    • 2011-07-15
    相关资源
    最近更新 更多