Saminda Peramuna
Saminda Peramuna

Reputation: 745

Spring Boot JPA Test fails with java.lang.IllegalArgumentException

I am trying to test my JPA repository interface. This is a simple Spring Boot web application which uploads and processes CSV files. The following is the repository I need to test.

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);
}

The test class I've created to test the above repository.

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);
    }
}

I have used the following gradle settings for testing.

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

When I run the tests I get the following errors.

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'

The error occurs when the TestEntityManager is trying to persist the data.

Upvotes: 0

Views: 707

Answers (1)

Michael Altenburger
Michael Altenburger

Reputation: 1336

You should edit the first line of your @Before method, so that it reads:

@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());
}

Currently you are using a local variable and manipulating this local variable. The instance variable file is never set and therefore you are trying to persist a null-object, which is of course not working.

Upvotes: 1

Related Questions