java - Spring Boot JPA 测试失败并出现 java.lang.IllegalArgumentException

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

我正在尝试测试我的 JPA 存储库接口(interface)。这是一个简单的 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 尝试保留数据时会发生错误。

最佳答案

您应该编辑 @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 从未设置过,因此您试图保留一个空对象,这当然是行不通的。

关于java - Spring Boot JPA 测试失败并出现 java.lang.IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47553060/

相关文章:

java - 如何使用 Spring 重新加载属性?

java - 在 Java 中从 List 路由方法调用的最佳方法

java - 无法解析的日期异常 : Formatting input date into a specified format

java - 使用 nativeQuery = true 在 JPA Reposity 中执行 @Query 时出现 ResultSet 错误

spring - 启用 AOP 会破坏我对采用字符串的工厂 bean 的依赖注入(inject)

java - Spring RestController POST 接受基本的 HTML 表单

java - 条件、谓词和规范之间有什么区别?

java - 命名查询和继承

java - 如何使用按钮(java)更改绘图的大小?

java - hibernate/JPA : Is it possible to retrieve heterogeneous entities in a single query?