Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.2K
Visualizações
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 ?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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)
over 4 years ago · Santiago Trujillo Relatório

0

Maybe not the most elegant workaround, but you can mock the behavior within a static block. Code in static block is executed before both @Before and @PostConstruct. I don't think, that mocking using annotations (@MockBean) would work, but it can also be done programatically.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda