I have a Java Spring application with a RedisService for interacting with a Redis database. The RedisService constructor takes a JedisPooled object as the constructor dependency for using the Redis connection:
@Repository public class RedisService { private final JedisPooled jedisPooled; @Autowired public RedisService(final JedisPooled jedisPooled) { this.jedisPooled = jedisPooled; } public String set(final String key, final String val) { return jedisPooled.set(key, val); } public String get(final String key) { return jedisPooled.get(key); } } I use a RedisServiceConfig class to manage the configuration for this service:
@Configuration public class RedisServiceConfig { @Bean public RedisService redisService(@Value("${redis.auth.password}") final String redisAuthPassword, @Value("${redis.endpoint}") final String redisEndpoint, @Value("${redis.port}") final int redisPort) { final JedisPooled jedisPooled; try { jedisPooled = new JedisPooled(redisEndpoint, redisPort, redisAuthPassword); } catch (final Exception e) { throw new JedisConnectionException("Error connecting to Redis"); } return new RedisService(jedisPooled); } } How can I unit test the exception handling in the config class? I've tried something like this, but I can't quite get it to work:
public class RedisServiceConfigTest { @Mock private JedisPooled mockJedisPooled; @InjectMocks private RedisServiceConfig redisServiceConfig; @Test public void testRedisServiceBeanCreation() { when(mockJedisPooled.created()).thenThrow(new JedisConnectionException("Connection error")); // I need something ^ like this? final RedisService redisService = redisServiceConfig.redisService("testPassword", "localhost", 6379); Assertions.assertNotNull(redisService); } } I've tried mocking the mockJedisPooled and tried to force it to throw exceptions. Is this the correct approach for unit testing a config class like this?
throw, I have removed the try/catch, thank you