Mockito @Before 方法在@PostConstruct 之后调用

Ric*_*rdK 1 java spring mockito kotlin spring-boot

这是我的简化代码:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MockitoSpringBootTest {

    @MockBean
    private MyBean myBean;


    @Before
    private void before(){
        Mockito.when(myBean.getSomeString()).thenReturn("TEST"));
    }

}

@Service
private class TestClass {

    @Autowired
    private MyBean myBean;

    @PostConstruct
    public void initialize() {
        myBean.getSomeString(); //SmartNull - method is not stubbed yet
    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是我需要存根MyBean方法,然后任何其他具有此对象自动装配的类将运行@BeforeClass方法。现在@Before方法是在@PostConstruct任何自动装配这个 bean 的类之后执行的(不止一个)。

MyBean 自动装配为模拟,但方法未存根,所以我得到:“此未存根方法调用返回的 SmartNull 对模拟:”

有没有办法在 Spring 容器初始化中设置模拟 bean 的优先级?

Suj*_*ith 7

使用@TestConfiguration 而不是使用@MockBean 可能有助于解决这个问题。

@TestConfiguration
    static class Configuration {
        @Bean
        public BeanToMock name() {
            // return mock object           
        }
    }
Run Code Online (Sandbox Code Playgroud)

并使用 @ContextConfiguration 注释测试类

@ContextConfiguration(classes = TestClassName.Configuration.class)
Run Code Online (Sandbox Code Playgroud)