quento
quento

Reputation: 1114

TestNG: Test method without arguments

It's time for me to write my first test. I was pretty exited about that, however I am stuck. I have method, which should verify installed Java version

    public static boolean verifyJavaVersion() throws UserException {
    if (System.getProperty("java.version") != null) {
        String[] javaProperty = System.getProperty("java.version").substring(2, System.getProperty("java.version").length()).split("\\.");
        int installedJavaVersion = Integer.parseInt(javaProperty[0]);
        int installedJavaReleaseVersion = Integer.parseInt(javaProperty[1].substring(2, javaProperty[1].length()));
        if (installedJavaVersion != REQUIRED_JAVA_VERSION || installedJavaReleaseVersion < MINIMUM_JAVA_RELEASE_VERSION)
            throw new UserException("Java version is not correct. Required Java version "
                    + REQUIRED_JAVA_VERSION + ", release " + MINIMUM_JAVA_RELEASE_VERSION + " or higher");
        return true;
    }
    throw new UserException("Java version not found");
}

I have 2 variables there, both of them are private static final, so, as you see, no arguments in this method. How can I test this method and should I test anything expect changing this 2 variables?

I have an idea to create public getters and setters for testing for those variables, but is this good practice?

Upvotes: 1

Views: 46

Answers (1)

Matsemann
Matsemann

Reputation: 21784

Realizing that writing a test is hard, often means that the code can be improved. And to me, that's one of the biggest reason to write tests: They force you to write better code!

If you look at your code snippet, it actually does several things:

  • It gets the version system property, possibly throwing an exception
  • It extracts the two versions and converts to integers
  • Then it compares them

When considering that, you see that this can be split into several functions. And they can be tested more easily.

public static boolean verifyJavaVersion() throws UserException {
    String javaVersion = ...
    int installedJavaVersion = extractJavaVersion(javaVersion);
    int installedJavaReleaseVersion = extractJavaReleaseVersion(javaVersion);
    checkVersion(installedJavaVersion, REQUIRED_JAVA_VERSION, installedJavaReleaseVersion, MINIMUM_JAVA_RELEASE_VERSION);
}

each of these should be easy to test.

I removed your null check for simplicity, but you see the idea.

Upvotes: 3

Related Questions