Spring Boot : Unit test hibernate's SequenceStyleGenerator

Viewed 273

I have a class which extends SequenceStyleGenerator for generating custom primary key for the database.

I'm asked to write test cases for the whole application. While I think that code coverage on SonaqQube can't be 100%, still I'm being asked to write the test cases for the whole application.

I've gone through the source code for SequenceStyleGenerator but I'm unable to get it how to test the class.

Here is the code for the same.

public class BigIntegerSequenceGenerator extends SequenceStyleGenerator {
    public static final String VALUE_PREFIX_PARAMETER = "valuePrefix";
    public static final String VALUE_PREFIX_DEFAULT = "";
    private String valuePrefix;
    public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
    public static final String NUMBER_FORMAT_DEFAULT = "%d";
    private String numberFormat;

    @Override
    public Serializable generate(SharedSessionContractImplementor session,
                                 Object object)  {
        return valuePrefix + String.format(numberFormat, super.generate(session, object));
    }

    @Override
    public void configure(Type type, Properties params,
                          ServiceRegistry serviceRegistry) {
        super.configure(LongType.INSTANCE, params, serviceRegistry);

        valuePrefix = ConfigurationHelper.getString(VALUE_PREFIX_PARAMETER,
                params, VALUE_PREFIX_DEFAULT);
        numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER,
                params, NUMBER_FORMAT_DEFAULT);
    }
}

Here is the test for this file

class BigIntegerSequenceGeneratorTest {

    SharedSessionContractImplementor session;
    BigIntegerSequenceGenerator generator;

    @BeforeEach
    void setUp() {
        generator = new BigIntegerSequenceGenerator();
        session = mock(SharedSessionContractImplementor.class);
        session = mock(Session.class);
    }

    @Test
    void testGenerate() {
        generator.generate(session,new Object());
    }

}

I'm getting

java.lang.NullPointerException
    at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:520)

I check it by using debug points and this is the code I'm getting.

@Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return optimizer.generate( databaseStructure.buildCallback( session ) );
    }

optimizer and databaseStructure are null.

For what I know, when the SpringBoot application runs, it automatically configures the hibernate and the optimizer and databaseStruictore are configured which will then be used for the models when saving the data.

I know that this will require the database connection mocking but it seems like I'm unable to do it.

NOTE : I'm using JUnit5 for testing

-Thank you

0 Answers
Related