Skip to content

Instantly share code, notes, and snippets.

@darekmydlarz
Last active May 14, 2021 16:08
Show Gist options
  • Save darekmydlarz/64196e54b84f136ec33ba7ecc34c1327 to your computer and use it in GitHub Desktop.
Save darekmydlarz/64196e54b84f136ec33ba7ecc34c1327 to your computer and use it in GitHub Desktop.
DbUnit - handle postgres JSONB in tests

Problem

I have entity with jsonb column type.

public class Copy {
    private Long id;

    @Column(columnDefinition = "jsonb")
    private String content;

    @Version
    private Instant version = Instant.now();
}

I am using Spring Test DbUnit.

When I run Spring integration tests I am getting error

org.dbunit.util.SQLHelper: copy.content data type (1111, 'jsonb') not recognized and will be ignored. 
See FAQ for more information.

Solution

You need to provide custom IDataTypeFactory which recognizes jsonb type.

@AllArgsConstructor
public class JsonbDataFactory extends DefaultDataTypeFactory {

    @Override
    public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException {
        if (sqlTypeName.equalsIgnoreCase("jsonb")) {
            return new JsonbDataType();
        }
        return super.createDataType(sqlType, sqlTypeName);
    }

}

Youu need to implement your own JsonbDataType

public class JsonbDataType extends AbstractDataType {
    JsonbDataType() {
        super("jsonb", Types.OTHER, String.class, false);
    }

    @Override
    public Object typeCast(Object value) {
        return value.toString();
    }
}

And in the end you need to register your custom DataTypeFactory in Spring Boot Test Context. Like this:

@SpringBootTest(webEnvironment = DEFINED_PORT)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class})
@Import(AbstractIT.MyTestConfiguration.class)
@DbUnitConfiguration(databaseConnection = "dbUnitDatabaseConnection")
public abstract class AbstractIT {

    @TestConfiguration
    static class MyTestConfiguration {
        @Bean
        DatabaseConfigBean configBean() {
            final DatabaseConfigBean configBean = new DatabaseConfigBean();
            configBean.setDatatypeFactory(new JsonbDataFactory());
            return configBean;
        }

        @Bean(name = "dbUnitDatabaseConnection")
        DatabaseDataSourceConnectionFactoryBean databaseDataSourceConnectionFactoryBean(DatabaseConfigBean configBean, DataSource dataSource) {
            DatabaseDataSourceConnectionFactoryBean factoryBean = new DatabaseDataSourceConnectionFactoryBean();
            factoryBean.setDatabaseConfig(configBean);
            factoryBean.setDataSource(dataSource);
            return factoryBean;
        }
    }

    // ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment