Extra conditional annotations for JUnit 4
There is an exception to every rule.
JConditions is an extension for JUnit framework, which allows to mark test methods with specific conditional annotations. This annotations allow to permit or restrict execution of test methods. It helps to keep clean your test methods using declarative programming and prevents a lot of unnecessary code (see Assume class).
A picture paints a thousand words:
@RunWith(ConditionTestRunner.class)
public class ExampleTest {
@Test
@RunningOnOS(LINUX)
public void testRunningOnOS() throws Exception {
// Check some Linux app
assertTrue(exec("some-linux-program"));
}
@Test
@IfJavaVersion(JAVA_8)
public void testIfJavaVersion8() {
// Check some Java 8 specific code
assertTrue(com.foo.Java8Class.isCorrect());
}
}
JConditions has the following conditional annotations:
This annotations could be used with test methods or/and classes (it will allow to run checks before each test method). You can also write custom annotations or make composite annotations.
JConditions uses JitPack.io for distribution, so you need to configure JitPack's Maven repository to fetch artifacts (dependencies).
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<dependencies>
<dependency>
<groupId>com.github.vbauer</groupId>
<artifactId>jconditions</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
repositories {
mavenCentral()
maven {
url 'https://jitpack.io'
}
}
dependencies {
testCompile 'com.github.vbauer:jconditions:1.2.3'
}
Some things that you need to know before exploring an examples:
@AppIsInstalled checks that specified application(s) is installed. It could be useful when developed application has an optional integrations with some external tools/apps and it will be good to check this integrations in tests.
@Test
@AppIsInstalled({ "ls", "uname" })
public void testAppIsInstalled() throws Exception {
exec("ls");
exec("uname");
}
@ExistsOnFS checks that specified file or directory is existed on file system. It is also possible to configure multiple values.
Available parameters:
@Test
@ExistsOnFS("pom.xml")
public void testFileExists() throws Exception {
Assert.assertTrue(FSUtils.fileExists("pom.xml"));
}
@HasClass checks that specified class(es) is available in classpath. It could be useful to check integration with optional features.
@Test
@HasClass("org.junit.Assert")
public void testHasClass() throws Exception {
Assert.assertNotNull(Class.forName("org.junit.Assert"));
}
@HasFreeSpace checks that FS element(s) / disk(s) has free space. It could be useful to check if it is possible to:
Available parameters:
@Test
@HasFreeSpace(value = { "/", "C:\\" }, min = 1024)
public void testHasFreeSpace() {
// Download some file
}
@HasPackage checks that specified package(s) is available in classpath. It could be useful to check integration with optional features.
@Test
@HasPackage("org.junit")
public void testHasPackage() throws Exception {
Assert.assertNotNull(Package.getPackage("org.junit"));
}
@IfJavaVersion checks that test is run on the specific version(s) of JVM.
EX: Some features could use external libraries and work only for the specific version of JVM. It is possible to check it, if you use full names for classes (class loader will load them in runtime).
@Test
@IfJavaVersion(IfJavaVersion.JAVA_8)
public void testIfJavaVersion8() {
Assert.assertTrue(IfJavaVersionChecker.javaVersion().contains("8"));
// Javaslang project works only on Java 8
Assert.assertNotNull(javaslang.Tuple0.instance());
}
@IfScript allows to write custom conditional rules using JSR 223: Scripting for the JavaTM Platform. JavaScript engine is available by default (it is part of JVM). All other JSR233-compatible languages will be included automatically if they are available in classpath.
Available parameters:
String
and Number
s)."js"
)."context"
variable.Parameters which are available in script context:
System.getenv()
).System.getProperties()
).System.console()
).context
provider.@Test
@IfScript("test.isSatisfiedInnerCheck")
public void testIfScriptNegative() {
Assert.fail();
}
@IgnoreIf allows to skip some test method using specific ConditionChecker
class.
It will skip test, if checker return true and execute method otherwise.
ConditionChecker
could be separate class, or nested static class, or even inner class.
It also works fine with private classes.
@Test
@IgnoreIf(Always.class)
public void testIgnoreIfAlways() {
Assert.fail();
}
@PropertyIsDefined checks if environment or system property is defined. It could be useful to simulate test profiles or to check some cases which are dependent on them (and could be optionals).
Available parameters:
@Test
@PropertyIsDefined(keys = "os.name")
public void testEnvVarIsDefined() {
Assert.assertNotNull(PropUtils.getSystemProperty("os.name"));
}
@ResourceIsAvailable allows to minimize code which is necessary to download some document/file via HTTP/HTTPS. It is also possible to cache downloaded resource between test executions, otherwise it will be remove after test.
Available parameters:
source
(default value is 10sec).@Test
@ResourceIsAvailable(
source = "http://apple.com",
target = "${java.io.tmpdir}/apple-homepage.html",
cache = false
)
public void testResourceIsAvailable() {
final String path = PropUtils.injectProperties("${java.io.tmpdir}/apple-homepage.html");
Assert.assertTrue(FSUtils.fileExists(path));
}
@RunIf is an opposite annotation to @IgnoreIf. It will run test method if ConditionChecker
returns true
.
@Test
@RunIf(SomeInnerClassCheck.class)
public void testInnerClass() {
Assert.fail();
}
@RunningOnOS checks the current operation system and runs test method only when it is specified and value
parameter.
It is also possible to configure multiple variants (to run test method, even one of them should be fine).
@Test
@RunningOnOS({
RunningOnOS.LINUX,
RunningOnOS.MAC,
})
public void testRunningOnOS() throws Exception {
Assert.assertTrue(exec("ls"));
}
@SocketIsOpened checks that specified socket is opened.
Available parameters:
@Test
@SocketIsOpened(host = "apple.com", port = 80)
public void testSocketIsOpened() throws Exception {
checkSite("http://apple.com");
}
@UrlIsReachable checks that specified URL address is reachable (available via URLConnection
).
It also possible to configure multiple URLs.
Available parameters:
@Test
@UrlIsReachable("http://apple.com")
public void testUrlIsReachable() throws Exception {
checkSite("http://apple.com");
}
It is possible use @IfRun
or @IgnoreIf
to run custom ConditionalChecker
,
but it is also possible to write your own annotation (like @HasPackage
or @IfScript
).
All JConditions out-of-box annotations was created using unified extension mechanism. This mechanism is centered around 3 main things:
@Condition
annotation which allows to glue custom annotation and conditional checker.Let's write an annotation which emulates standard JUnit's @org.junit.Ignore
:
@Condition(IgnoreItChecker.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD })
public @interface IgnoreIt {
}
public class IgnoreItChecker implements ConditionChecker<IgnoreIt> {
@Override
public boolean isSatisfied(final CheckerContext<IgnoreIt> context) {
return false;
}
}
That's all! Now, you can mark test classes or test methods with @IgnoreIt
to skip test(s).
Sometimes it could be useful to have possibility to resolve the following cases (to prevent unnecessary code):
It is possible, because JConditions extension mechanism resolves all hierarchy of classes and annotations.
Let's make an annotation which allows to detect if our MySQL database works fine:
@SocketIsOpened(host = "localhost", port = 3306)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD })
public @interface MySQLWorks {
}
Let's make an annotation which allows to run tests only on Linux machines with Java 8:
@RunningOnOS(LINUX)
@IfJavaVersion(JAVA_8)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD })
public @interface OnLinuxWithJava8 {
}
JConditions uses Maven for its build. To build project, run:
mvn clean install -P strict
from the root of the project directory.
Profile strict
is necessary to check code style and to run static code analysis.
Copyright 2015 Vladislav Bauer
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
See LICENSE file for details.