I have a Spring @Service and @Scope("prototype") class named StringCircularQueue, which has a constructor where a variable named queueName is getting initialized and a method addElement as below. To unit test this method inside the class, I am using JUnit Mockito to mock the RedisConnectionConfig which is being used in the addElement method.
When debugging the test, the redisConnectionConfig variable inside the addElement method shows null. But, if I comment out the constructor and run the same, the redisConnectionConfig variable shows a Non Null value.
Unable to figure out what is the issue when using the constructor. Any suggestions could be of great help.
@Service
@Scope("prototype")
public class StringCircularQueue {
@Autowired
private RedisConnectionConfig redisConnectionConfig;
private String queueName;
public StringCircularQueue(String queueName) {
this.queueName = queueName;
}
public Boolean addElement(String element) {
RedissonClient redisClient = redisConnectionConfig.getRedisClient();
// Some other business logic
}
}
public class RedisCircularQueueTest {
@InjectMocks
RedisStringCircularQueue redisStringCircularQueue;
@Mock
private RedisConnectionConfig redisConnectionConfig;
@Mock
private RedissonClient redissonClient;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAddElementToQueue() {
Mockito.when(redisConnectionConfig.getRedisClient()).thenReturn(redissonClient);
Boolean isAdded = redisStringCircularQueue.addElement("testString");
Assert.assertEquals(true, isAdded);
}
}