开发者

Is it possible for e JUnit test to tell if it's running in Eclipse (rather than ant)

I have a test that compares a large blob of expected XML with the actual XML received. If the XML is significantly different, the actual XML is written to disk for analysis and the test fails.

I would prefer to use assertEquals so that I can compare the XML more easily in Eclipse - but this could lead to very large JUnit and CruiseControl lo开发者_运维技巧gs.

Is there a way I can change a JUnit test behaviour depending on whether it's running through Eclipse or through Ant.


Here are 2 solutions.

Use system properties

boolean isEclipse() {
    return System.getProperty("java.class.path").contains("eclipse");
}

Use stacktrace

boolean isEclipse() {
    Throwable t = new Throwable();
    StackTraceElement[] trace = t.getStackTrace();
    return trace[trace.length - 1].getClassName().startsWith("org.eclipse");
}


Yes - you can test if certain osgi properties are set (System.getProperty("osgi.instance.area") for instance). They will be empty if junit is started through ant outside of eclipse.


Maybe the "java.class.path" approach can be weak if you include some eclipse jar in the path.

An alternative approch could be to test "sun.java.command" instead:

On my machine (openjdk-8):

sun.java.command    org.eclipse.jdt.internal.junit.runner.RemoteTestRunner ...

A possible test:

boolean isEclipse() {
    return System.getProperty("sun.java.command")
      .startsWith("org.eclipse.jdt.internal.junit.runner.RemoteTestRunner");
}


Usually, the system proeprties are different in different environments. Try to look for a system property which is only set by eclipse or ant.

BTW: The output in eclipse is the same, its just that the console for eclipse renders the output in a more readable form.

Personally, I wouldn't worry about the size of the logs. Generally you don't need to keep them very long and disk space is cheap.


With Java 1.6+, it looks like the result of System.console() makes a difference between running for Eclipse or from a terminal:

boolean isRealTerminal()
{
    // Java 1.6+
    return System.console() != null;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜