Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we do a For-Each Assertion?

Tags:

java

assert

Hi all I was wondering how do I put an entire block of code within an assertion?

For example, I have an array and I would like to do assertions on each value of the array. This is what my code looks like:

for (int value : values) {
    assert Within(value, x, y);
}

But of course if I run the program without -ea whereby the assertions are turned off, the loop still exists.

I was wondering how do I put the entire loop in an assertion statement?

EDIT:

argh dang Java is really too rigid at times, I ended up doing something functional like this:

assert Every(value, new F1<Boolean, Integer>() {
    Boolean Call(Integer value) {
        return Within(value, 0, 255);
    }
});
like image 883
Pacerier Avatar asked Nov 19 '11 13:11

Pacerier


1 Answers

You can use a method

public boolean check(int... values) {
    for (int value : values) 
        if(!Within(value, x, y)) return false;
    return true;
}

assert check(values);

Another approach is to test for assertion if you have lots of checks

boolean assertEnabled = false;
assert assertEnabled = true;
if (assertEnabled) {
   // do lots of checks
}
like image 65
Peter Lawrey Avatar answered Nov 07 '22 13:11

Peter Lawrey