Last active
March 6, 2019 07:41
-
-
Save kkarad/3800994 to your computer and use it in GitHub Desktop.
SpringTest setup example with mock properties loaded during context initialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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