使用系统属性的示例,在 build.gradle 中设置,从 Java 应用程序读取(从评论中的问题跟进):
基本上,使用中的test
任务build.gradle
,使用测试任务方法systemProperty
设置在运行时传递的系统属性:
apply plugin: 'java'
group = 'example'
version = '0.0.1-SNAPSHOT'
repositories {
mavenCentral()
// mavenLocal()
// maven { url 'http://localhost/nexus/content/groups/public'; }
}
dependencies {
testCompile 'junit:junit:4.8.2'
compile 'ch.qos.logback:logback-classic:1.1.2'
}
test {
logger.info '==test=='
systemProperty 'MY-VAR1', 'VALUE-TEST'
}
这是示例代码的其余部分(您可能可以推断,但无论如何都包含在此处):它获取一个系统属性MY-VAR1
,预计在运行时设置为VALUE-TEST
:
package example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
static final Logger log=LoggerFactory.getLogger(HelloWorld.class);
public static void main(String args[]) {
log.info("entering main...");
final String val = System.getProperty("MY-VAR1", "UNSET (MAIN)");
System.out.println("(main.out) hello, world: " + val);
log.info("main.log) MY-VAR1=" + val);
}
}
测试用例:如果MY-VAR
未设置,测试应该失败:
package example;
...
public class HelloWorldTest {
static final Logger log=LoggerFactory.getLogger(HelloWorldTest.class);
@Test public void testEnv() {
HelloWorld.main(new String[]{});
final String val = System.getProperty("MY-VAR1", "UNSET (TEST)");
System.out.println("(test.out) var1=" + val);
log.info("(test.log) MY-VAR1=" + val);
assertEquals("env MY-VAR1 set.", "VALUE-TEST", val);
}
}
运行(注意:测试通过):
$ gradle cleanTest test
:cleanTest
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test
BUILD SUCCESSFUL
我发现棘手的部分实际上是从 gradle 获取输出......所以,这里配置了日志记录(slf4j+logback),并且日志文件显示了结果(或者,运行gradle --info cleanTest test
;还有一些属性可以让标准输出控制台,但是,你知道,为什么):
$ cat app.log
INFO Test worker example.HelloWorld - entering main...
INFO Test worker example.HelloWorld - main.log) MY-VAR1=VALUE-TEST
INFO Test worker example.HelloWorldTest - (test.log) MY-VAR1=VALUE-TEST
如果您注释掉“ systemProperty...
”(顺便说一句,它只适用于test
任务),那么:
example.HelloWorldTest > testEnv FAILED
org.junit.ComparisonFailure at HelloWorldTest.java:14
为了完整起见,这里是 logback 配置(src/test/resources/logback-test.xml
):
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>app.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d %p %t %c - %m%n</pattern>
</layout>
</appender>
<root level="info">
<appender-ref ref="FILE"/>
</root>
</configuration>
文件:
build.gradle
src/main/java/example/HelloWorld.java
src/test/java/example/HelloWorldTest.java
src/test/resources/logback-test.xml