How can I get a list of instantiated beans from Spring?

前端 未结 6 753
挽巷
挽巷 2020-12-05 07:50

I have several beans in my Spring context that have state, so I\'d like to reset that state before/after unit tests.

My idea was to add a method to a helper class wh

6条回答
  •  离开以前
    2020-12-05 08:20

    I had to improve it a little

    @Resource
    AbstractApplicationContext context;
    
    @After
    public void cleanup() {
        resetAllMocks();
    }
    
    private void resetAllMocks() {
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        for (String name : context.getBeanDefinitionNames()) {
            Object bean = beanFactory.getSingleton(name);
            if (Mockito.mockingDetails(bean).isMock()) {
                Mockito.reset(bean);
            }
        }
    }
    

提交回复
热议问题