spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.72k stars 38.15k forks source link

Provide a way to not reset `@MockitoBean` before performing tests #33941

Open quaff opened 12 hours ago

quaff commented 12 hours ago
package com.example;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;

import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@ContextConfiguration
@SpringJUnitConfig
public class MockBeanTests {

    @MockitoBean
    // @MockBean works
    ContextRefreshedEventProcessor contextRefreshedEventProcessor;

    @Test
    void test() {
        then(contextRefreshedEventProcessor).should().process(any(ContextRefreshedEvent.class));
    }

    @Configuration
    static class Config {

        @Bean
        ContextRefreshedEventListener contextRefreshedEventListener(
                ContextRefreshedEventProcessor contextRefreshedEventProcessor) {
            return new ContextRefreshedEventListener(contextRefreshedEventProcessor);
        }

    }

    static class ContextRefreshedEventListener {

        private final ContextRefreshedEventProcessor contextRefreshedEventProcessor;

        public ContextRefreshedEventListener(ContextRefreshedEventProcessor contextRefreshedEventProcessor) {
            this.contextRefreshedEventProcessor = contextRefreshedEventProcessor;
        }

        @EventListener
        public void onApplicationEvent(ContextRefreshedEvent event) {
            contextRefreshedEventProcessor.process(event);
        }

    }

    interface ContextRefreshedEventProcessor {
        void process(ContextRefreshedEvent event);
    }
}

The test failed with @MockitoBean but works fine with boot's @MockBean, I think it's caused by @MockitoBean reset mock before tests automatically.