Search code examples
javaspring-bootjunit4

Get @ConfigurationProperties bean autowired in Junit


enter code hereI have a class annotated with @ConfigurationProperties in spring boot, how can I get this bean autowired in Junit tests

@ConfigurationProperties
 public class ConfigClass{
   public String property;
}

--Now under Test--

@RunWith(MockitoJunitRuner.class)
 class MyTests{

 @Autowired
 private ConfigClass configClass;

 @Test
 public myTest1(){
   String prop = configClass.getProperty();
   //Some assert
 }

-- configClass is coming out as null when I run this test --


Solution

  • testing springboot with jUnit you can use @RunWith(SpringRunner.class) or @SpringbootTest which loads the entire context

    if you want to test your config specifically use @TestConfiguration annotation. There are two ways of using the annotation Either on a static inner class in the same test class where we want to @Autowire the bean or create a separate test configuration class:

    i will pick the first option inside static class

    see example below ,

    @ConfigurationProperties
     public class ConfigClass{
       public String property;
    }
    --Now under Test--
    
    @RunWith(MockitoJunitRuner.class)
     class MyTests{
    
    
     @Autowired
     private ConfigClass configClass;
    
    **// here use the @TestConfiguration annotation not @Test**
    
     @TestConfiguration
     public myTest1(){
       String prop = configClass.getProperty();
       //Some assert
     }
    

    //Ok this works, now there is another class like below which is part of the test, and the configClass is not getting autowired there, any ideas

    NB: i suggest to use the second option which is having separate test configuration class to autowire all configurations across the classs like below

    @TestConfiguration
    public YourTestConfigurationClass ()
    {
    // plus all the other code which worked 
    
        @Component
        public class OtherClass{
     
          @Autowired
          private ConfigClass configClass;
       }
    }