Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito @Before method is called after @PostConstruct

This is my simplified code:

@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
    }

}

My problem is that I need to stub MyBean methods, before any other class which has this object autowired will run @BeforeClass method. Right now @Before method is executed after @PostConstruct of any class which is autowiring this bean (there's more than one).

MyBean is autowired as a mock, but method is not stubbed, so I get: "SmartNull returned by this unstubbed method call on a mock:"

Is there any way to set priority of mocked bean in Spring container initialization ?

like image 285
RichardK Avatar asked Jun 11 '26 22:06

RichardK


1 Answers

Using @TestConfiguration rather than using the @MockBean might help to solve this problem.

@TestConfiguration
    static class Configuration {
        @Bean
        public BeanToMock name() {
            // return mock object           
        }
    }

And annotating the test class with @ContextConfiguration:

@ContextConfiguration(classes = TestClassName.Configuration.class)
like image 167
Sujith Avatar answered Jun 13 '26 10:06

Sujith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!