I'm getting this ClassCastException during testing one of my services:
java.lang.ClassCastException: class java.math.BigInteger cannot be cast to class java.lang.Integer (java.math.BigInteger and java.lang.Integer are in module java.base of loader 'bootstrap')
In that service there are multiple createNativeQuery-counts like this:
Query queryCount = em.createNativeQuery(sqlCount);
return (Integer)queryCount.getSingleResult();
When i fix the castexception to that:
return ((BigInteger)queryCount.getSingleResult()).intValue();
Then the tests are succesful but sadly iam getting an ClassCastException when i start the application and calling the service with the "real" Db2 Database. In that case BigInteger cannot be casted to Integer.
application-h2test.properties:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DB2Dialect
Config
@Configuration
@EnableTransactionManagement
public class SomethingConfig {
//...
@Bean
@Profile("h2test")
@ConfigurationProperties(prefix = "spring.datasource")
DataSource h2DataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl(
"jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=DB2");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
//...
}
SomethingServiceTest
@ActiveProfiles("h2test")
@SpringBootTest
class SomethingServiceTest {
@Autowired
SomethingService sut;
@Test
void givenYWhenXThenZ() {
this.sut.getSomething(); //In the Implementation the ClassCastException is thrown
}
}
data.sql
SET MODE DB2;
I have tried several things, for example I have changed the dialect (DB2390,DB2400) and the mode in the application properties or the config.
The only solution i have currently in mind, is that i could catch the ClassCastException and when the Exception happens i will cast it to the Biginteger so that the test is successful.
However, I don't like to implement logic into a service that the test is succesful. Do you have another approach / idea ?
((Number)queryCount.getSingleResult()).intValue();
should do the job.