I have some beans defined in a spring boot project, BeanA:
@Component
public class BeanA {
public String getName() {
return "A";
}
}
and BeanB:
@Component
public class BeanB {
@Autowired
private BeanA beanA;
private String name;
@PostConstruct
public void init() {
this.name = beanA.getName();
}
public String getName() {
return this.name;
}
}
when I mock the beanA.getName, it return null
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MockitoTestApplication.class })
public class BeanTest {
@Autowired
private BeanB beanB;
@MockBean
private BeanA beanA;
@Before
public void mock() {
MockitoAnnotations.initMocks(this);
Mockito.doReturn("mockA").when(beanA).getName();
}
@Test
public void testGetName() {
System.out.println(beanB.getName()); // return null here
}
}
I guess there is some bean load priority here, what's the root cause and how to fix it?