spring - what is the idiomatic way to use ConfigurationProperties and EnableConfigurationProperties in tests? -
i trying setup unit tests elements used within spring(-boot) application, , struggled setup around configurationproperties
, enableconfigurationproperties
. way got work doesn't seem consistent examples have seen in have witnessed needing both configurationproperties
, enableconfigurationproperties
on configuration class, doesn't seem right, , hoping might provide guidance.
here simplified example:
javatestconfiguration.java
package com.kerz; import org.springframework.boot.context.properties.configurationproperties; import org.springframework.boot.context.properties.enableconfigurationproperties; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import javax.validation.constraints.notnull; @configuration @configurationproperties @enableconfigurationproperties public class javatestconfiguration { public void setfoo(string foo) { this.foo = foo; } @notnull string foo; @bean string foo() { return foo; } }
javatestconfigurationtest.java
package com.kerz; import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowired; import org.springframework.test.context.contextconfiguration; import org.springframework.test.context.testpropertysource; import org.springframework.test.context.junit4.springjunit4classrunner; import static org.junit.assert.assertequals; @runwith(springjunit4classrunner.class) @contextconfiguration(classes = {javatestconfiguration.class}) @testpropertysource("classpath:test.properties") public class javatestconfigurationtest { @autowired string foo; @test public void shouldwork() throws exception { assertequals("foo", "bar", foo); } }
test.properties
foo=bar
your test more integration test if starting spring context. therefore should test production spring configuration.
i advise not create testing configuration. use 1 production configuration testing.
you using @testpropertysource
annotation, used when need define test specific properties. if can test prod configuration not use it.
Comments
Post a Comment