@TestPropertySource и @PropertySource не работают для JUnit
Кажется, что ничего в Spring 4.1.17 с Spring Boot 1.2.6.RELEASE работает вообще. Я просто хочу получить доступ к свойствам приложения и, при необходимости, переопределить их при необходимости (без использования взлома для непосредственного ввода PropertySource)
это не работает.
@TestPropertySource(properties = {"elastic.index=test_index"})
и не делает этого.
@TestPropertySource(locations = "/classpath:document.properties")
и не..
@PropertySource("classpath:/document.properties")
полный тестовый сценарий.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@TestPropertySource(properties = {"elastic.index=test_index"})
public class PropertyTests {
@Value("${elastic.index}")
String index;
@Configuration
@TestPropertySource(properties = {"elastic.index=test_index"})
static class ContextConfiguration {
}
@Test
public void wtf() {
assertEquals("test_index", index);
}
}
в результате чего
org.junit.ComparisonFailure:
Expected :test_index
Actual :${elastic.index}
Кажется, что существует много противоречивой информации между 3.x и 4.x, и я не могу найти ничего, что сработает наверняка.
Любое понимание будет с благодарностью оценено. Ура!
Ответы
Ответ 1
Отличается лучшим образом (до тех пор, пока Spring не зафиксирует этот недосмотр) не будет PropertySourcesPlaceholderConfigurer
, который приведет к test.properties(или тому, что вы хотите) и @Import
или продолжите это @Configuration
.
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import java.io.IOException;
@Configuration
public class PropertyTestConfiguration {
@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws IOException {
final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocations(ArrayUtils.addAll(
new PathMatchingResourcePatternResolver().getResources("classpath*:application.properties"),
new PathMatchingResourcePatternResolver().getResources("classpath*:test.properties")
)
);
return ppc;
}
}
Это позволяет вам определять значения по умолчанию в application.properties и переопределять их в test.properties. Конечно, если у вас несколько схем, то вы можете настроить класс PropertyTestConfiguration
по мере необходимости.
И используйте это в unit test.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class PropertyTests {
@Value("${elastic.index}")
String index;
@Configuration
@Import({PropertyTestConfiguration.class})
static class ContextConfiguration {
}
}
Ответ 2
Я использовал locations
свойство @TestPropertySource
переопределить (или добавить) свойство.
Это сработало для меня (весна 4.2.4):
@TestPropertySource(locations = {
"classpath:test.properties",
"classpath:test-override.properties" })
Но переопределения таких свойств, как ниже, не было:
@TestPropertySource(
locations = {"classpath:test.properties"},
properties = { "key=value" })
Несмотря на то, что javadoc говорит, что эти свойства имеют наивысший приоритет. Может быть, ошибка?
Обновить
Ошибка должна быть исправлена в Spring boot версии 1.4.0 и выше. См. Фиксацию, которая закрывает проблему. К настоящему времени свойства, объявленные в представленном виде, должны иметь приоритет.
Ответ 3
Для использования @Value требуется PropertySourcesPlaceholderConfigurer bean для разрешения ${...}
заполнителей. См. Принятый ответ здесь: @Возможно не устанавливать через тестовый контекст, настроенный Java
Ответ 4
Для Me @TestPropertySource ( "classpath: xxxxxxxx.properties" ) работал
Ответ 5
Пробовали ли вы использовать @PropertySource("classpath:document.properties")
или @PropertySource("classpath*:document.properties")
?