Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 222
nflacco Avatar asked Nov 17 '25 21:11

nflacco


2 Answers

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"
like image 108
nflacco Avatar answered Nov 19 '25 10:11

nflacco


For those of you who might have struggled to let assertion works under SBT project, this might be helpful to you.

I tried both fork := true javaOptions += "-ea" and even sbt "show run-options" proves that the the flag is in the javaOptions. For some miracle reason, the assertion is still not working when running.

I am not sure whether this is a SBT bug or what. But not until I use export _JAVA_OPTIONS="-ea" did the sbt run finally log Picked up _JAVA_OPTIONS: -ea.

I hope this helps cuz I literally spend 3 hours on this.

like image 29
Randolph Zeng Avatar answered Nov 19 '25 10:11

Randolph Zeng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!