Enabling Java assertions when using SBT to manage assemblies

This is the first time in a while that I am doing Java programming outside of Eclipse (for coursera algo course) and I am trying to use SBT to build. SBT works fine (slow start) but I can't figure out how to enable assertions. None 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
    }
}

      

+3


source to share


3 answers


This link explains it. The short version is used below in the build.sbt file:



// Enable assertions
fork in run := true

javaOptions in run += "-ea"

      

+3


source


For those of you who have struggled to let the approval work for the SBT project, this might be helpful for you.

I've tried both fork := true

javaOptions += "-ea"

and it even sbt "show run-options"

proves that the flag is in javaOptions. For some miraculous reason, this statement still doesn't work at work.



I'm not sure if this is a SBT bug or what. But so far I don't use export _JAVA_OPTIONS="-ea"

the sbt finally log command Picked up _JAVA_OPTIONS: -ea

.

Hope this helps because I'm literally spending 3 hours on this.

+1


source


I'm wondering why you need to include assertions in an assembly.

The parameter -ea

allows you to check the assertion when your program starts. This is a parameter java

, not a parameter javac

. You don't need (and AFAIK cannot) enable / disable assertions in your code at build time.

0


source







All Articles