4

I'm having trouble understanding how assert in java works. I want to make so that if the assert is not true then the test should fail. The following example should returns false but the test does not fail. What I'm I missing?

Example:

package test;

public class tests {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        tests s = new tests();
        s.approve(500);
    }
    public   boolean approve(int age)
    {
        assert (age < 60) :"Test Failed" ;
        if (age > 100)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
1
  • 1
    Is -ea passed to the VM? By default assertions are disabled. Commented Jan 9, 2016 at 20:38

3 Answers 3

4

You need to enable assertions with the -ea flag.

You probably don't want to use assert though, but a proper testing framework that has its own assertion methods.

Sign up to request clarification or add additional context in comments.

Comments

2

Condition age < 60 is true for age equal to 50. Therefore the condition will succeed and the assert will not fail.

Assert will fail when the condition is false.

1 Comment

Updated, but it still does not fail
0

The thing to understand about asserts as that they're intended only for the development phase. They're not a part of the solution you're delivering to your client, they're a way of catching bugs early in your development phase. That's why you turn them off in production.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.