Skip to content

Instantly share code, notes, and snippets.

@kkarad
Last active March 6, 2019 07:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkarad/3800994 to your computer and use it in GitHub Desktop.
Save kkarad/3800994 to your computer and use it in GitHub Desktop.
SpringTest setup example with mock properties loaded during context initialization
package ork.kkarad.examples;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.mock.env.MockPropertySource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = BaseSpringTest.CustomAnnotationConfigContextLoader.class)
public class BaseSpringTest{
@Autowired
Service service;
@Test
public void testIt() throws Exception {
service.doSomething();
}
@Configuration
@Import(AnotherConfiguration.class)
static class ContextConfiguration {
@Bean
protected PropertyRetriever retriever() {
return new PropertyRetriever() {
@Override
public void addListener(PropertyListener listener) {
throw new UnsupportedOperationException();
}
};
}
}
static class CustomAnnotationConfigContextLoader extends AnnotationConfigContextLoader {
@Override
protected void customizeContext(GenericApplicationContext context) {
MockPropertySource source = new MockPropertySource()
.withProperty("my.prop.key", "value");
context.getEnvironment().getPropertySources().addFirst(source);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment