This example demonstrates how to use @IfProfileValue.
@IfProfileValue annotation is used on JUnit tests (doesn't work for others). When used on a method, which is also annotated with @Test, the method will be ignored given that: for a specified property key, the corresponding specified value (or one of the values; we can specify multiple values) does not match with any runtime Environment properties.
By default, it only works for Java system property but we can change that by implementing a custom ProfileValueSource (we will see that in the next tutorial). By default SystemProfileValueSource(an implementation of ProfileValueSource) is used which uses system properties as the underlying source.
When @IfProfileValue is used on the class level, all methods can be ignored based on the same condition.
Example
Creating a Spring application
@Service
public class MyService {
public String getMsg() {
return "some msg";
}
}
@Configuration
@ComponentScan
public class AppConfig {
}
The JUnit test
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class MyServiceTests {
@Autowired
private MyService myService;
@Test
@IfProfileValue(name = "os.name", values = {"Windows 10", "Windows 7"})
public void testMyService() {
String s = myService.getMsg();
System.out.println(s);
Assert.assertEquals("some msg", s);
}
} mvn -q test -Dtest=MyServiceTests -DfailIfNoTests=false Outputd:\example-projects\spring-core-testing\if-profile-value-annotation>mvn -q test -Dtest=MyServiceTests -DfailIfNoTests=false
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.logicbig.example.MyServiceTests some msg Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.372 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
If run on other O.S or simply property value doesn't match, then the test will be skipped:
D:\example-projects\spring-core-testing\if-profile-value-annotation>mvn -q test -Dtest=MyServiceTests -DfailIfNoTests=false
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.MyServiceTests
Tests run: 1, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.138 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 1
Example ProjectDependencies and Technologies Used: - spring-context 4.3.8.RELEASE: Spring Context.
- spring-test 4.3.9.RELEASE: Spring TestContext Framework.
- junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- JDK 1.8
- Maven 3.3.9
|