0
votes

I am trring to read a value from the properties file in my junit setup using spring boot. I can not read the value. Below is my content:-

application-test.properties

my.user.name=Amar

COnfig file to create beans:

@Configuration
@ActiveProfiles("test")
@Profile("test")
public class RdbmsTestConfig {

    @Value("${my.user.name}")
    private String name;

    @Bean
    public String myString(){
        return "Amar";
    }

    @Bean
    public PropsHolder propsHolder() {
        PropsHolder propsHolder = new PropsHolder();
        propsHolder.setUserName(name);
        return propsHolder;
    }
 }

My test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
public class TestRoomService {

    @Autowired
    @Qualifier("myString")
    private String myString;

    @Autowired
    private PropsHolder propsHolder;

    @Autowired
    private Environment env;

    @Test
    public void userTest() {
        Arrays.stream(env.getActiveProfiles()).forEach(System.out::println);
        System.out.println(propsHolder.getUserName());
        Assert.assertNotNull(myString);
        Assert.assertEquals("Amar",myString);
    }
}

The value for propsHolder.getUserName comes out to be ${my.user.name}

3

3 Answers

2
votes

First remove @ActiveProfiles("test") from your class RdbmsTestConfig. Then your test just defines the RdbmsTestConfig as spring context. As I can see you do not run a real spring boot test. The problem is you do not have any PropertyPlaceholderConfigurer configured in your spring config. So either configure one PropertyPlaceholderConfigurer or add @SpringBootTest to your test if you have any SpringBootApplication.

0
votes

I've never used @Profile(), so i'm not sure if that is supposed to do what you want it to do. But I'm always using @PropertySources(), because otherwise, how is the code supposed to know where to look for the properties?

@Configuration
@PropertySources(value = { @PropertySource("classpath:core-
test.properties") })
0
votes

I created a base test class that has the required annotations:-

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
@SpringBootTest
public abstract class BastTest { }

@ActiveProfiles set the profile to use used, I dont have to mention it in the application.properties file

My test class now extends this:-

public class TestRoomService extends BastTest 

In my RdbmsTestConfig remove @ActiveProfiles annotation.