3

My Junit is not picking up properties set in test properties file. I get no error, but value returned from properties file is null

CLASS TO BE TESTED:

package com.abc.mysource.mypackage;

@Component
@ComponentScan
public class MyHelper {

    @Autowired
    @Qualifier("commonProperties")
    private CommonProperties commonProperties;  

    public LocalDateTime method1ThatUsesCommonProperties(LocalDateTime startDateTime) throws Exception {
        String customUserType = commonProperties.getUserType(); // Returns null if run as JUnit test
        //Further processing
    }
}

SUPPORTING COMPONENTS - BEANS & CONFIG CLASSES:

package com.abc.mysource.mypackage;
@Component
public class CommonProperties {
     @Value("${myhelper.userType}")
     private String userType;

         public String getUserType() {
        return userType;
    }
    public void setCalendarType(String userType) {
        this.userType = userType;
    }
}

CONFIG CLASS:

package com.abc.mysource.mypackage;
@Configuration
@ComponentScan(basePackages ="com.abc.mysource.mypackage.*")
@PropertySource("classpath:default.properties")
public class CommonConfig {}

default.properties under src/main/resources

myhelper.userType=PRIORITY

MY TEST CLASS:

package com.abc.mysource.mypackage.test;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=MyHelper.class)
@TestPropertySource("classpath:default-test.properties")
@EnableConfigurationProperties
public class MyHelperTest {
    @MockBean(name="commonProperties")
    private CommonProperties commonProperties;

    @Autowired
    private MyHelper myHelper;

    @Test
    public void testMethod1ThatUsesCommonProperties() {
        myHelper.method1ThatUsesCommonProperties();
    }
}

default-test.properties defined under /src/test/resources:

myhelper.userType=COMMON

NOTE:

I moved default-test.properties to /src/main/resources - commonProperties.getUserType() is null

I even used @TestPropertySource(properties = {"myhelper.userType=COMMON"}). Same result

NOTE 2:

I tried the solution on @TestPropertySource is not loading properties.

This solution requires me to create a duplicate bean called CommonProperties under src/test/java. But @MockBean fails when I do

@MockBean(name="commonProperties")
private CommonProperties commonProperties;

Please do not mark a duplicate.

NOTE 3: Mine is a spring, not a spring boot application.

Deepboy
  • 523
  • 3
  • 16
  • 28

1 Answers1

1

MockBeans are suited if you don't need specific state. Usually this bean is "isolated" and every method call of this bean will have the same result. It is "isolated" -> the service that uses @Value annotation will not apply on this bean.

What you need is a "normal" bean, properly constructed and initialized. Please use @Autowired annotation and define another bean if needed, using a test profile.

Adina Rolea
  • 2,031
  • 1
  • 7
  • 16