Search code examples
springspring-bootcucumbercucumber-jvmcucumber-java

Destroying bean of a given package and create again before each cucumber scenario (test) to prevent state from leaking between scenarios


I am trying to destroy the beans before each test. So that when a test start running it should create fresh beans to execute the test as required classes are Autowired.

I am using destroyBean method of ConfigurableListableBeanFactory.

@Autowired
private ConfigurableListableBeanFactory beanFactory;

val beanClass = Class.forName(beanDefinition.getBeanClassName());
val beans = beanFactory.getBeansOfType(beanClass);
beanFactory.destroyBean(bean);

I am expecting the constructor to be called before each test as I am destroying all the beans. But it is not calling the constructor and using the old beans.


Solution

  • @Scope("cucumber-glue")
    

    Placing the above annotation on top of each bean fixed the problem. Sample -

    @Component
    @Scope("cucumber-glue")
    public class TestComponent {
    
    }