Search code examples
javaspringjunit5

Import a specific bean in JUnit5 without load all application


I have a configuration class on my project

@Configuration
public class MyConfiguration {

    //client SDK configuration build
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
    
}

Now I want to use this bean on my unit test class without load all application context

@ExtendWith(MockitoExtension.class)
@ContextConfiguration(classes = {MyConfiguration.class})
public class Test {

    @Autowired
    private MyBean mybean;

    @Test
    public void methodTest() {
        //use mybean class methods
        mybean.method();
    }

}

But I am getting an NullPointerException error when run the test (in the line where I invoke mybean definition)

What could be wrong ?

Thanks


Solution

  • Replace

    @ExtendWith(MockitoExtension.class)
    

    with

    @ExtendWith(SpringExtension.class)
    

    SpringExtension enables the use of Spring with JUnit5. Once you have that, JUnit will call the extension, which in turn will read the Spring annotations.