这是我的简化代码:
@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
}
}
我的问题是,我需要 stub MyBean
方法,然后任何其他 Autowiring 此对象的类将运行 @BeforeClass
方法。现在,@Before
方法在 Autowiring 该 bean 的任何类的 @PostConstruct
之后执行(有多个)。
MyBean 作为模拟 Autowiring ,但方法未 stub ,因此我得到:“模拟上的此未 stub 方法调用返回的 SmartNull:”
有没有办法在 Spring 容器初始化中设置模拟 bean 的优先级?
最佳答案
使用@TestConfiguration
而不是使用@MockBean
可能有助于解决此问题。
@TestConfiguration
static class Configuration {
@Bean
public BeanToMock name() {
// return mock object
}
}
并使用@ContextConfiguration
注释测试类:
@ContextConfiguration(classes = TestClassName.Configuration.class)
关于java - Mockito @Before 方法在 @PostConstruct 之后调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54570738/