Thiagarajan Ramanathan
Thiagarajan Ramanathan

Reputation: 1124

How to write test case for Spring boot Application class with properties dependency - Could not resolve placeholder

I followed the below StackOverflow page and wrote test case for Application class How to test main class of Spring-boot application

When I run my test case I get the following error

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'http.client.connection.timeout' in value "${http.client.connection.timeout}"
.....

I have added @TestPropertySource("classpath:test-manifest.yml") in my test case.

test-manifest.yml has 'http.client.connection.timeout'

My Testcase

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mypackage.Application;

@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource("classpath:test-manifest.yml")
@SpringBootTest
public class MainTest {

    @Test
    public void main() {
        Application.main(new String[] {});
    }
}

How to make it work? Any help is appreciated.

Upvotes: 0

Views: 408

Answers (1)

Lesiak
Lesiak

Reputation: 25946

TestPropertySource does not support yaml configuration files.

Check https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html

Supported File Formats

Both traditional and XML-based properties file formats are supported — for example, "classpath:/com/example/test.properties" or "file:/path/to/file.xml".

See also TestPropertySourceUtils.addPropertiesFilesToEnvironment():

try {
    for (String location : locations) {
        String resolvedLocation = environment.resolveRequiredPlaceholders(location);
        Resource resource = resourceLoader.getResource(resolvedLocation);
        environment.getPropertySources().addFirst(new ResourcePropertySource(resource));
    }
}

ResourcePropertySource can only deal with .properties files and not .yml. In regular app, YamlPropertySourceLoader is registered and can deal with .

Possible solutions:

Either change your config to .properties or rely on profiles to load your test config.

Upvotes: 2

Related Questions