Spring profiles on integration tests class - spring

we have selenium tests which are ran by java test class.
On local environment everything is ok, but I want to switch off those tests when run on jenkins.
So I use:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebIntegrationTest("server.port=1234")
#Profile("!jenkins")
#ActiveProfiles("integrationtests")
public class LoginAndEditProfileSeleniumTest {
...
What works:
running mvn clean test run all tests locally, with integrationtests profile active. I dont want to pass any additional parameter.
What I want to achieve:
running mvn clean test -Dspring.profiles.active=jenkins switch off this test.
Can I merge somehow profile passed by parameter, ActiveProfile annotation and take Profile annotation into consideration? :)
//update:
Its possible to use class extending ActiveProfilesResolver:
public class ActiveProfileResolver implements ActiveProfilesResolver {
#Override
public String[] resolve(Class<?> testClass) {
final String profileFromConsole = System.getProperty("spring.profiles.active");
List<String> activeProfiles = new ArrayList<>();
activeProfiles.add("integrationtests");
if("jenkins".contains(profileFromConsole)){
activeProfiles.add("jenkins");
}
return activeProfiles.toArray(new String[activeProfiles.size()]);
}
}
but it seems to not to cooperate with #Profile anyway ( jenkins profile is active but test is still running ) .

#Profile has zero affect on test classes. Thus, you should simply remove that annotation.
If you want to enable a test class only if a given system property is present with a specific value, you could use #IfProfileValue.
However, in your scenario, you want to disable a test class if a given system property is present with a specific value (i.e., if spring.profiles.active contains jenkins).
Instead of implementing a custom ActiveProfileResolver, a more elegant solution would be to use a JUnit assumption to cause the entire test class to be ignored if the assumption fails.
This should work nicely for you:
import static org.junit.Assume.*;
// ...
#BeforeClass
public static void disableTestsOnCiServer() {
String profilesFromConsole = System.getProperty("spring.profiles.active", "");
assumeFalse(profilesFromConsole.contains("jenkins"));
}
Regards,
Sam (author of the Spring TestContext Framework)

Related

Is it possible to only load specific Annotations based on a profile?

Is it possible to only load specific Annotations only during tests or only during a run in Spring Boot?
I am facing a situation where there are Annotations affecting the tests, yet work well in the live run, so wanted to know whether it was possible to exclude them only during tests, but include them when running, similar to how one can include specific beans based on a Spring profile
Apologies if this has been asked before, I have tried searching to no avail
You could use the #ConditionalOnProperty annotation which creates a bean depending on which property (in the application.properties -> app.val = false) is set. For example for a service:
#Service
#ConditionalOnProperty(name = "app.val", havingValue = "false")
public class TestService {
...
}
Also you could use the #Profile annotation and annotate them to the methods which have for example a test profile (defined in the application.properties as well -> spring.profiles = test).
#Profile({"test"})
public String getValue() {
return "test value";
}
#Profile({"production"})
public String getValue() {
return "production value";
}

Active profile in SpringBootTest based on system variable

As the host of Redis is different in local and CI, my #Tests can pass locally, they can't pass in CI.
Firstly, I tried to mock the RedisTemplate like this:
RedisTemplate redisTemplate = mock(RedisTemplate.class);
ValueOperations valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.increment(anyString(), anyLong())).thenReturn(1L);
when(valueOperations.get("a#a.com")).thenReturn("1");
It did mocked RedisTemplate, but can't mock redisTemplate.opsForValue() and valueOperations.increment(...) ( I can't find reason )
Then, I wrote two profiles named application-ci-test.yml and applicaiton-test.yml, tried to active one of them based on system environment variable
I learnd from here that I can set active profile in this way:
#Configuration
public class MyWebApplicationInitializer
implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter(
"spring.profiles.active", "dev");
}
}
and this way:
#Autowired
private ConfigurableEnvironment env;
...
env.setActiveProfiles("someProfile");
But I don't know how to use them. The system variable can get by System.getenv(..). So now I want to know how to active profile based on the variable I get.
I found a way to active corresponding profile based on system variable or property:
import org.springframework.test.context.ActiveProfilesResolver;
public class SpringActiveProfileResolver implements ActiveProfilesResolver {
#Override
public String[] resolve(Class<?> testClass) {
final String isCITest = System.getEnv("isCITest");
return new String[] { isCITest == null ? "test" : "ci-test" };
}
}
then use the parameter resolver in #ActiveProiles:
#ActiveProfiles(resolver = SpringActiveProfileResolver.class)
How to set environment variable is anther issue, and answers above have already answered it
Assuming your #Test methods are in a class with the #SpringBootTest annotation, you can use #ActiveProfiles to set the profile.
#SpringBootTest
#ActiveProfiles("someProfile")
Use run parameters inside your CI job/script.
Depending how You start Your tests, You can for example do it with VM arguments
mvn test -Dspring.profiles.active=ci-test
or
java -jar -Dspring.profiles.active=ci-test
or whatever.
On the other hand you can use program arguments:
java -jar --spring.profiles.active=ci-test
One way or the other, providing active profile at start will activate property file of your choice.
If you want some specific piece of code (configuration class for example) to be run with specific profile only, annotate that piece of code with #Profile("ci-test")
Example:
#Configuration
#Profile("ci-test")
public class SomeConfiguration {
//any configuration beans etc.
}
Following class will only be loaded when Your active profile will be "ci-test". So if You run Your app on Your CI server with one of the commands above, both property file named "ci-test" and this configuration class will get loaded.
It's also worth adding that in order for some code to run in ALL profiles EXCEPT specified, you can negate the name inside profile annotation like: #Profile("!ci-test").
Code annotated like that will run with all profiles (including default) except "ci-test".

how to pre-populate spring properties from tests

I've a slight race condition when it comes to loading spring properties for an integration test using #TestPropertySource.
Consider the following;
test (using Spock but same for JUnit)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#TestPropertySource(locations = "classpath:test/simple-test.properties")
class SimpleStuff extends Specification {
public static final String inputDirectoryLocation = "/tmp/input-test-folder"
def "test method"() {
//do test stuff
}
}
simple-test.properties
inputDirectoryLocation=/tmp/input-test-folder
Spring Component
#Component
class SpringComponent {
#Value('${inputDirectoryLocation}')
String inputDirectory;
//do other stuff
}
The above works fine but how would I make the test fully isolated and NOT have a dependency on the FileSystem having the folder /tmp/input-test-folder (as not all users running this test are allowed to create a /tmp folder on their FS)
For example, I would like to use something like
inputDirectoryLocation = Files.createTempDirectory()
so that
#Value('${inputDirectoryLocation}')
String inputDirectory;//equals the output of Files.createTempDirectory()
resulting in test using the OS default temporary folder location & allows us to have the test simply delete the temp folder on cleanup. Is there an eloquent solution to solve the above?
Note: using Spring boot 1.5
Turned out simple enough - simply had to change the value in the properties file to refer to the
inputDirectoryLocation=${java.io.tmpdir}/input-test-folder
Then have my Spock specification create the temp folder prior to launching Spring (by using the setup() fixture method )

Change locale for JUnit tests via Spring context

All tests are launched by gradle.
I'd like to define the locale for all JUnit tests on a project. At first I thought about the following way:
public class TestCases {
static Locale defaultLocale = Locale.getDefault();
#BeforeClass
public static void setDefaultLocale() {
Locale.setDefault(Locale.UK);
}
// here goes bunch of tests
// ...
#AfterClass
public static void restoreLocale() {
Locale.setDefault(defaultLocale);
}
}
But it is too cumbersome, as I have hundreds of files to be changed.
I found also that running single test with -Duser.language=en parameter (I use Intellij) will do the job. But I am not able to change gradle scripts in order to provide this solution.
Is there any way to define Locale for JUnit tests via Spring context? Or maybe there is an other better way? Thanks.
One way to achieve this would be to add a test lifecycle hook that is fired before your suite is executed.
test.beforeSuite { TestDescriptor suite ->
System.setProperty('user.language', 'en')
}

Retrieve and Modify the #ConfigurationContext programmatically via code?

How to Retrieve and Modify the #ConfigurationContext programmatically via code ?
I have a default configuration where it contains valid xml files.
Now i need to add an invalid configuration for a particular test case and test the same.
How to override, retrieve and modify the #ConfigurationContext programmatically via code ?
Thanks in advance,
Kathir
Disclaimer: I am assuming you are using JUnit since you didn't comment differently in your reply to my comment.
I think what you are trying to do does not make lot of sense, in my opinion it is still better to create a dedicated test class for your not-working configuration in order to be able to do more than one test. However:
annotate your test class with #RunWith(SpringJUnit4ClassRunner.class) and #ContextConfiguration(locations = {"classpath:/working-context.xml"}). In this way you can retrieve the configuration context in two ways: first, you can simply declare a field #Inject ApplicationContext context which will contain the working context. Or, you make your test class implements ApplicationContextAware and then write a public void setApplicationContext (ApplicationContext applicationContext). I would go for the second one since it will come in hand for changing the context programmatically.
write a not-working-context.xml and place it in your classpath
in the test method you want to fail, reload the application context with context = setApplicationContext(new ClassPathXmlApplicationContext("not-working-context.xml")); and test all the errors you like.
though it is not good practice to stand on test case order, make sure your failing test will be executed as the last one (tests are executing alphabetically) so you don't have to reload the working context in the other tests.
In the end your test class will look like:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:/working-context.xml"})
public class TestClass implements ApplicationContextAware {
private ApplicationContext context;
public void setApplicationContext(ApplicationContext context){
this.context = context;
}
//Other tests
#Test
public void zFailingTest() {
context = setApplicationContext(new ClassPathXmlApplicationContext("not-working-context.xml"));
//your test
}
}

Resources