Dynamiite
Dynamiite

Reputation: 1499

Using Assert Java

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;
        }
    }
}

Upvotes: 4

Views: 201

Answers (3)

MiguelMunoz
MiguelMunoz

Reputation: 4962

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.

Upvotes: 0

Kayaman
Kayaman

Reputation: 73578

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.

Upvotes: 4

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18865

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.

Upvotes: 2

Related Questions