Search code examples
javasbtassertions

Enabling java assertions when using SBT to manage builds


For the first time in a while I'm doing java programming outside of Eclipse (for coursera algo course) and I'm trying to use SBT for builds. SBT works fine (slow to start though) but I cannot figure out how to enable assertions. Neither of the following seem to work.

javaOptions += "-ea" // doesn't work
javaOptions in run += "-ea" // doesn't work either

build.sbt

// disable using the Scala version in output paths and artifacts
crossPaths := false

// Enable assertions?
javaOptions += "-ea" // doesn't work
//javaOptions in run += "-ea" // doesn't work either

organization := "me"

name := "me"

version := "1.0-SNAPSHOT"

// Use jars from parent dir. Normally jars are stuck in lib/
unmanagedJars in Compile += file("../stdlib.jar")

unmanagedJars in Compile += file("../algs4.jar")

QuickFind.java

import java.util.Arrays; // I hate java so much

public class QuickFind {
    public int[] id;

    public QuickFind (int N) {
        id = new int[N];
        int i;
        for (i = 0; i < N; i++) {
            id[i] = i;
        }
    }

    public boolean connected (int p, int q) {
        return id[p] == id[q];
    }

    public void union (int p, int q) {
        // Walk through array and make everything with id = p || q
        // equal to id p
        int pid = id[p];
        int qid = id[q];

        int i;
        for (i = 0; i < id.length; i++) {
            if (id[i] == qid) id[i] = pid;
        }
    }

    public static void main (String[] args) {
        StdOut.println("QuickFind"); // from stdlib.jar
        QuickFind uf = new QuickFind(4);
        uf.union(0,1);

        // Assert unions work
        StdOut.println("array=" + Arrays.toString(uf.id));
        assert uf.connected(0,1);
        assert uf.connected(0,2); // <---------------------this should fail
    }
}

Solution

  • This link explains it. The short version is use the below in your build.sbt:

    // Enable assertions
    fork in run := true
    
    javaOptions in run += "-ea"